0

这让我很困惑。为什么第一行有效,而当我动态创建对象时却无效?

$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..
4

2 回答 2

1

命名空间在编译时解析。当您尝试从字符串创建对象时,您必须定义类的绝对路径。像这样的东西:

$className = "\\Vendor\\Package\\Strategy\\NotificationStrategy";

或者

$className = __ NAMESPACE __."\\Strategy\\NotificationStrategy";
于 2013-02-27T22:52:33.660 回答
0

嗯......我尝试了类似于你所做的事情:

策略.php:

<?php
    namespace Strategy{

      class NotificationStrategy{
        public function hello(){ echo "Hi!\n"; }
      }
    }
?>

实例化.php

<?php
  require 'strategy.php';

  $ns    = new Strategy\NotificationStrategy();
  $klass = "Strategy\\NotificationStrategy";
  $qq    = new $klass();

  $qq->hello(); // Hi!
?>

这对我来说很好,所以如果你遇到问题,那会让我认为你有需要问题......也许你的动态调用试图在包含类定义的文件的包含之前触发?

于 2013-02-27T22:57:00.577 回答