How can I get the callee in PHP? [duplicate]

陌路散爱 提交于 2019-11-29 15:20:52
alexn

Edit: Sorry, saw your note about debug_backtrace() now.

Kinda ugly but hey, if you need to do this something is wrong.

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'];
}

Outputs:

init..

bar called from foo

foo called from bar

Why dont you simply use OO and declare your method/function private?

If you start sprinkling those get_callee() all over your code, you are creating a horrible kludge.

Xdebug provides some nice functions.

<?php
  Class MyClass
  {
    function __construct(){
        $this->callee();
    }
    function callee() {
        echo sprintf("callee() called @ %s: %s from %s::%s",
            xdebug_call_file(),
            xdebug_call_line(),
            xdebug_call_class(),
            xdebug_call_function()
        );
    }
  }
  $rollDebug = new MyClass();
?>

will return trace

callee() called @ /var/www/xd.php: 16 from MyClass::__construct

To install Xdebug on ubuntu the best way is

sudo aptitude install php5-xdebug

You might need to install php5-dev first

sudo aptitude install php5-dev
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!