Cho*_*ter 6 php language-features
可能的重复:
PHP 5 中的调用函数?
我想知道从哪里调用全局函数或公共方法。我想我可以通过检查 debug_backtrace 来做到这一点,但我宁愿使用一种更轻量级的机制(如果存在)。有什么建议么?
例如,如果您想象 get_callee() 函数和常量存在:
function doSomething() {
if(get_callee() == 'PHP_GLOBAL') { throw new IllegalAccessException(); }
...
}
Run Code Online (Sandbox Code Playgroud)
编辑:抱歉,现在看到您关于 debug_backtrace() 的注释。
有点难看,但是嘿,如果你需要这样做,那就错了。
神奇之处在于 get_callee() 函数和 debug_backtrace()。是的,如果您必须使用它,请添加一些错误检查。
<?php
init();
function foo()
{
echo 'bar called from ' . get_callee() . '<br />';
bar();
}
function bar()
{
echo 'foo called from ' . get_callee() . '<br />';
}
function init()
{
echo 'init.. <br />';
foo();
}
function get_callee()
{
$backtrace = debug_backtrace();
return $backtrace[1]['function'];
}
Run Code Online (Sandbox Code Playgroud)
输出:
在里面..
从 foo 调用的 bar
foo 从酒吧调用