Mã nói tốt hơn so với dòng chữ:namespace tương đối và 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');
Như nhận xét, nếu tôi sử dụng tên đủ điều kiện bên trong call_user_func()
nó hoạt động như mong đợi, nhưng nếu tôi sử dụng tên tương đối es nó nói rằng lớp học không được tìm thấy – nhưng các hoạt động instantiations trực tiếp. Tôi có thiếu một số thứ gì đó hoặc lạ của mình theo thiết kế?
Tôi tin rằng điều này là do thiết kế. Quy tắc tương tự áp dụng cho các hàm như 'define()', 'constant()', v.v. Kiểm tra [chú thích này] (http://www.php.net/manual/en/function.defined.php#110530) . – Passerby