使用 PHP 5.3 命名空间按字符串实例化类
问题描述:
我无法解决使用字符串变量和 PHP 5.3 实例化新类的问题.命名空间.例如,这是有效的;
I can't get around an issue instantiating a new class by using a string variable and PHP 5.3. namespaces. For example, this works;
$class = 'Reflection';
$object = new $class();
然而,这不是;
$class = 'ApplicationLogMyClass';
$object = new $class();
抛出一个致命错误,说明找不到该类.然而,如果使用 FQN,它显然可以被实例化,即;
A fatal error gets thrown stating the class cannot be found. However it obviously can be instantiated if using the FQN i.e.;
$object = new ApplicationLogMyClass;
我发现这在 PHP 5.3.2-1 上是显而易见的,但在更高版本中则不然.有没有办法解决这个问题?
I've found this to be aparrent on PHP 5.3.2-1 but not not in later versions. Is there a work around for this?
答
$class = 'ApplicationLogMyClass';
$object = new $class();
开头的 引入了一个(完全限定的)命名空间标识符,但它不是类名本身的一部分.
The starting introduces a (fully qualified) namespaced identifier, but it's not part of the class name itself.