代碼說話勝於言:相對命名空間和call_user_func()
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](http://www.php.net/manual/en/function.defined.php#110530) 。 – Passerby