learning php
learning php

Reputation: 1264

when it is required that a class will be defined before instantiation?

In the PHP documentation it says:

Classes should be defined before instantiation (and in some cases this is a requirement).

can some one give me a example of a class that can not be instantiated unless it was previously defined?

Upvotes: 4

Views: 116

Answers (2)

choniwaniwani
choniwaniwani

Reputation: 1

<?php
// Top Level

trait T {
}

$c = new C();

class C {
    use T;
}

With trait, this code occurs error (Class 'C' not found in...).

Upvotes: 0

deceze
deceze

Reputation: 522155

if (true) {
    new Foo;
    class Foo { }
}

The parsing rules are the same as for functions: if they're defined in the "top level" of a file, they're parsed during, well, parsing of the file. If they're defined inside a piece of code which requires runtime evaluation, then the class or function will only be defined when the code is executed, in which case you can't use it before it's been "executed".

Upvotes: 4

Related Questions