这让我很困惑。为什么第一行可以工作,而当我动态创建对象时,它却不能?
$a = new Strategy\NotificationStrategy(); // This works
$className = "Strategy\\NotificationStrategy";
var_dump(class_exists($className)); // bool(false)
$strategy = new $className(); // Fatal error: Class 'Strategy\NotificationStrategy' not found, etc..发布于 2013-02-28 06:52:34
命名空间在编译时解析。当你尝试从字符串创建对象时,你必须定义类的绝对路径。如下所示:
$className = "\\Vendor\\Package\\Strategy\\NotificationStrategy";或
$className = __ NAMESPACE __."\\Strategy\\NotificationStrategy";发布于 2013-02-28 06:57:01
嗯……我尝试了和你类似的方法:
strategy.php:
<?php
namespace Strategy{
class NotificationStrategy{
public function hello(){ echo "Hi!\n"; }
}
}
?>instantiate.php
<?php
require 'strategy.php';
$ns = new Strategy\NotificationStrategy();
$klass = "Strategy\\NotificationStrategy";
$qq = new $klass();
$qq->hello(); // Hi!
?>这对我来说很好,所以如果你有问题,这会让我认为你的动态调用在包含类定义的文件的include之前尝试触发了require issues...perhaps?
https://stackoverflow.com/questions/15123730
复制相似问题