コードは言葉よりも上手に話します:
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()
と期待どおりに機能しますが、相対名前空間を使用すると、クラスが見つからなかったと表示されますが、直接インスタンス化は機能します。設計上、何かが足りないのでしょうか、それとも奇妙なのでしょうか。