这令我感到困惑。为什么第一行是有效的,当我动态创建对象时,它不会?
$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..
答案 0 :(得分:1)
命名空间在编译时解析。当您尝试从字符串创建对象时,您必须定义类的绝对路径。像这样:
$className = "\\Vendor\\Package\\Strategy\\NotificationStrategy";
或
$className = __ NAMESPACE __."\\Strategy\\NotificationStrategy";
答案 1 :(得分:0)
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!
?>
这对我很有用,所以如果你遇到问题,这会让我觉得你有需要的问题......也许你的动态调用试图在包含该文件的包含之前触发类定义?