Question

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 ;
?>
Was it helpful?

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.

OTHER TIPS

If you call a trait inside your class it will through an error:

<?php
$class = "a";
$ob = new $class();

class a {
    var $city = "New York";
    use myTrait;
}

I don't know why but that problem have kept me busy for 2 days.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top