使用 PHP 5.3 命名空间按字符串实例化类 [英] Instantiating class by string using PHP 5.3 namespaces

查看:32
本文介绍了使用 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.

这篇关于使用 PHP 5.3 命名空间按字符串实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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