相对名称空间和call_user_func() [英] Relative namespaces and 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()
中使用全限定名,它会按预期工作,但如果使用相对名称空间,则表示找不到该类.但是直接实例化是可行的.我是否故意遗漏了某些东西或它的奇怪?
As commented, if I use the full-qualified name inside call_user_func()
it works as expected, but if I use relative namespaces it says the class was not found – but direct instantiations works. Am I missing something or its weird by design?
推荐答案
您必须在回调中使用完全限定的类名.
You have to use the fully qualified classname in callbacks.
请参见示例#3 call_user_func()
使用名称空间名称
See Example #3 call_user_func()
using namespace name
<?php
namespace Foobar;
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0
我相信这是因为call_user_func
是来自全局范围的函数,同时也从全局范围执行回调.无论如何,请参见第一句话.
I believe this is because call_user_func
is a function from the global scope, executing the callback from the global scope as well. In any case, see first sentence.
另请参见上面的说明示例#2动态访问命名空间元素,其中指出
Also see the note aboveExample #2 Dynamically accessing namespaced elements which states
必须使用标准名称(带有名称空间前缀的类名称).
One must use the fully qualified name (class name with namespace prefix).
这篇关于相对名称空间和call_user_func()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!