instantiation class before defined

怎甘沉沦 提交于 2019-12-08 03:08:09

问题


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 ;
?>

回答1:


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.



来源:https://stackoverflow.com/questions/21436699/instantiation-class-before-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!