代码胜于雄辩:
命名空间.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()
它会按预期工作,但如果我使用相对名称空间,它会说找不到该类——但直接实例化是有效的。我是否遗漏了某些东西,或者它的设计很奇怪?