duanqi5114
duanqi5114
2014-01-29 16:21

定义之前的实例化类

  • php
  • instantiation
  • class
已采纳

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条回答

  • douqiao5543 douqiao5543 7年前

    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.

    点赞 3 评论 复制链接分享