如何使用PHP获取被调用方? [英] How can I get the callee in PHP?
问题描述
可能重复:
PHP 5中的调用函数?
Possible Duplicate:
Caller function in PHP 5?
我想知道从哪里调用全局函数或公共方法.我想我可以通过检查debug_backtrace来做到这一点,但如果有的话,我宁愿使用轻量级的机制.有什么建议吗?
I would like to know from where a global function or public method is being called. I guess I could do it by inspecting debug_backtrace but I'd rather use a lighterweight mechanism if one exists. Any suggestions?
例如类似的事情,如果您想象get_callee()函数和现有常量存在:
For example something like so, if you imagine the get_callee() function and constant existing:
function doSomething() {
if(get_callee() == 'PHP_GLOBAL') { throw new IllegalAccessException(); }
...
}
推荐答案
抱歉,现在看到了有关debug_backtrace()的注释.
Kinda丑陋,但是,嘿,如果您需要这样做,那是错误的.
Kinda ugly but hey, if you need to do this something is wrong.
神奇之处在于get_callee()函数和debug_backtrace().是的,如果必须使用此功能,请添加一些错误检查.
The magic is in the get_callee() function and debug_backtrace(). And yes, add some error checking if you must use this.
<?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'];
}
输出:
init ..
init..
从foo调用的栏
从酒吧打来的foo
这篇关于如何使用PHP获取被调用方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!