【发布时间】:2013-01-18 21:27:03
【问题描述】:
代码胜于雄辩:
namespaces.php:
<?php
namespace foo;
use foo\models;
class factory
{
public static function create($name)
{
/*
* Note 1: FQN works!
* return call_user_func("\\foo\\models\\$name::getInstance");
*
* Note 2: direct instantiation of relative namespaces works!
* return models\test::getInstance();
*/
// Dynamic instantiation of relative namespaces fails: class 'models\test' not found
return call_user_func("models\\$name::getInstance");
}
}
namespace foo\models;
class test
{
public static $instance;
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
public function __construct()
{
var_dump($this);
}
}
namespace_test.php:
<?php
require_once 'namespaces.php';
foo\factory::create('test');
正如评论的那样,如果我在 call_user_func() 中使用完全限定名称,它会按预期工作,但如果我使用相对名称空间,它会说找不到该类 - 但直接实例化有效。我是否遗漏了某些东西或它的设计奇怪?
【问题讨论】:
-
我相信这是设计使然。相同的规则适用于
defined()、constant()等函数。查看this comment。
标签: php namespaces