实例化类之前定义 [英] instantiation class before defined

查看:136
本文介绍了实例化类之前定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在php.net中写入以下内容:
类应该在实例化之前定义(在某些情况下这是一个要求)。
任何人都可以给出一个例子,当需要时?因为一个典型的使用它不需要,像这个例子中工作正常:

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


推荐答案

这不起作用:

new Foo;

if (true) {
    class Foo { }
}

有条件声明的类必须先来。基本上,在文件的顶层的任何东西在解析文件时由解析器直接处理,这是运行时环境执行代码之前的步骤(包括 new Foo )。但是,如果类声明嵌套在之类的语句中,如果,则需要由运行时环境进行评估。即使该语句被保证为真,解析器也不能评估 if(true),因此类的实际声明被推迟到运行时。在运行时,如果你尝试在类Foo {} 之前运行 new 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.

这篇关于实例化类之前定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆