使用 PHP 5.3 命名空间通过字符串实例化类
我无法解决使用字符串变量和 PHP 5.3 实例化新类的问题。命名空间。例如,这有效;
$class = 'Reflection';
$object = new $class();
然而,这并不;
$class = '\Application\Log\MyClass';
$object = new $class();
抛出致命错误,指出找不到该类。然而,如果使用 FQN ,它显然可以被实例化,即;
$object = new \Application\Log\MyClass;
我发现这在 PHP 5.3.2-1 上很明显,但在更高版本中则不然。有解决办法吗?
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();
However, this does not;
$class = '\Application\Log\MyClass';
$object = new $class();
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;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
起始
\
引入了一个(完全限定的)命名空间标识符,但它不是类名本身的一部分。The starting
\
introduces a (fully qualified) namespaced identifier, but it's not part of the class name itself.实现相同结果但使用动态参数的另一种方法如下。请将下面的类视为您要实例化的类。
然后:
如果您没有使用最新版本的 PHP,请使用以下代码替换上面示例的最后一行:
该代码将产生以下输出:
Another way to achieve the same result but with dynamic arguments is as follows. Please consider the class below as the class you want to instantiate.
And then:
If you are not using a recent version of PHP, please use the following code that replaces the last line of the example above:
The code will produce the following output:
我遇到了同样的问题,并且找到了解决这个问题的方法。可能效率不是很高,但至少有效。
I had the same problem and I have found some way around this problem. Probably not very efficient, but at least works.