Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
Caller function in PHP 5?

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?

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(); }
     ...
}
like image 357
Chocky Chockster Avatar asked Feb 28 '23 05:02

Chocky Chockster


2 Answers

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

like image 125
alexn Avatar answered Mar 13 '23 05:03

alexn


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.

like image 32
Anti Veeranna Avatar answered Mar 13 '23 06:03

Anti Veeranna