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

查看:294
本文介绍了使用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 = '\Application\Log\MyClass';
$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 \Application\Log\MyClass;

我发现这在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 = 'Application\Log\MyClass';
$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天全站免登陆