问题描述
我想知道是否可以确定调用函数时当前的名称空间是什么.我有此函数声明:
I was wondering if it was possible to determine what the current namespace was when the function was being called. I have this function declaration:
<?php
namespace Site\Action;
function add ($hook, $function) {
/**
* determine the namespace this was called from because
* __NAMESPACE__ is "site\action" :(
*/
if (is_callable($function))
call_user_func($function);
}
?>
在另一个文件上:
<?php
namespace Foo;
function bar () {
}
?>
让我们说这是我的程序代码:
And let's say I have this as my procedural code:
<?php
namespace Foo;
Site\Action\add('hookname', 'bar');
?>
假设在这种情况下Bar
旨在解析为Foo\bar
是有道理的,因为这是从其调用的名称空间.
It would make sense to assume that Bar
in this case was intended to resolve as Foo\bar
since that was the namespace it was called from.
这是一个很长的解释,因此,是否可以确定调用Site\Action\add()
的活动名称空间?
That was a long explanation so again, is it possible to determine the active namespace where Site\Action\add()
was called from?
谢谢.
推荐答案
您正在寻找的是: ReflectionFunctionAbstract :: getNamespaceName
如果您想知道您来自 debug_backtrace() a>是你的朋友.
What you are looking for is : ReflectionFunctionAbstract::getNamespaceName
If you want to know where you're coming from debug_backtrace() is your friend.
function backtrace_namespace()
{
$trace = array();
$functions = array_map(
function ($v) {
return $v['function'];
},
debug_backtrace()
);
foreach ($functions as $func) {
$f = new ReflectionFunction($func);
$trace[] = array(
'function' => $func,
'namespace' => $f->getNamespaceName()
);
}
return $trace;
}
只需从任何地方调用它即可查看回溯.我修改了您的过程"代码文件,如下所示:
Just call it from anywhere to see the backtrace.I modified your "procedural" code file as follows:
namespace Foo;
function bar ()
{
var_export(backtrace_namespace());
}
/** The unasked question: We need to use the fully qualified name currently. */
function go()
{
\Site\Action\add('hookname', 'Foo\\bar');
}
go();
The Result from including this file will be the following on stdout:
array (
0 =>
array (
'function' => 'backtrace_namespace',
'namespace' => '',
),
1 =>
array (
'function' => 'Foo\\bar',
'namespace' => 'Foo',
),
2 =>
array (
'function' => 'call_user_func',
'namespace' => '',
),
3 =>
array (
'function' => 'Site\\Action\\add',
'namespace' => 'Site\\Action',
),
4 =>
array (
'function' => 'Foo\\go',
'namespace' => 'Foo',
),
)
Now for bonus points the answer to the hidden question:
The following will allow you to call the function as you intended:
Site\Action\add('hookname', 'bar');
So before you redesign try this on for size:
namespace Site\Action;
function add($hook, $function)
{
$trace = backtrace_namespace();
$prev = (object) end($trace);
$function = "$prev->namespace\\$function";
if (is_callable($function))
call_user_func($function);
}
我看不出为什么不应该使用debug_backtrace
的原因,这就是它的用途.
I see no reason why debug_backtrace
should not be used, this is what it is there for.
这篇关于确定调用该函数的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!