在PHP中获取被调用类的替代方法

时间:2017-07-31 14:59:39

标签: php

除了debug_backtrace()之外还有另一种方法可以知道调用我脚本的类的名称吗?

2 个答案:

答案 0 :(得分:2)

如果您只想要当前的类名,可以使用get_class(); 如果调用堆栈涉及许多类,并且你想要第一个类,那么你真的必须使用debug_backtrace()。

$className = get_class($this);

答案 1 :(得分:2)

据我所知back_trace是最好的方法。也就是说,如果你想获得调用脚本的类/文件等,你可以使用这个函数

 /**
 * get the line this file was called on ( +1 )
 * @param number $offset
 * @return array
 */
function trace($offset = 0)
{
    $trace = debug_backtrace(false);
    foreach ($trace as $t) {
        if ($t['file'] != __FILE__) {
            break;
        }
        ++$offset;
    }
    return array_slice($trace, ($offset - count($trace)));
}

基本上,当你遍历回溯时,你正在寻找当前文件之前的项目。

如果您希望在调用trace()函数的位置之前说出1个位置,也可以设置$offset

https://github.com/ArtisticPhoenix/Evo/blob/master/Evo/Debug.php