instantiation class before defined
class, instantiation, php
Solution
This won't work:
new Foo;
if (true) {
class Foo { }
}
Conditionally declared classes must come first. Basically, anything that's at the "top level" of the file is handled directly by the parser while parsing the file, which is the step before the runtime environment executes the code (including `new Foo`). However, if a class declaration is nested inside a statement like `if`, this needs to be evaluated by the runtime environment. Even if that statement is guaranteed to be true, the parser cannot evaluate `if (true)`, so the actual declaration of the class is deferred until runtime. And at runtime, if you try to run `new Foo` before `class Foo { }`, it will fail.
Problem
in php.net the following is written: Classes should be defined before instantiation (and in some cases this is a requirement). can anyone give an example when it is required? because a typical use of it doesn't require, like in this example that works ok: ``` <?php $class = "a" ; $ob = new $class() ; class a { var $city = "new york" ; } echo $ob->city ; ?> ```