Determine where the function was called with PHP

Do you guys know how I can determine from which file the function called inside this function was?

I was thinking about using debug_backtrace .. but it doesn't look like an elegant way to do this, and they also list other reasons in another question here

So what are the other alternatives?

Many thanks

+5
source share
5 answers

Inside a function debug_backtrace()is the only way to determine the caller, unless, of course, you pass this information as a parameter.

Please note that you cannot use the default values ​​for this. For example:.

function f($param1, $param2, $caller=__FUNCTION__) ...

__FUNCTION__ , . , f.

+2

, , debug_backtrace(). , :

function backtrace(){
    $backtrace = debug_backtrace();

    $output = '';
    foreach ($backtrace as $bt) {
        $args = '';
        foreach ($bt['args'] as $a) {
            if (!empty($args)) {
                $args .= ', ';
            }
            switch (gettype($a)) {
                case 'integer':
                case 'double':
                    $args .= $a;
                    break;
                case 'string':
                    //$a = htmlspecialchars(substr(, 0, 64)).((strlen($a) > 64) ? '...' : '');
                    $args .= "\"$a\"";
                    break;
                case 'array':
                    $args .= 'Array('.count($a).')';
                    break;
                case 'object':
                    $args .= 'Object('.get_class($a).')';
                    break;
                case 'resource':
                    $args .= 'Resource('.strstr($a, '#').')';
                    break;
                case 'boolean':
                    $args .= $a ? 'TRUE' : 'FALSE';
                    break;
                case 'NULL':
                    $args .= 'Null';
                    break;
                default:
                    $args .= 'Unknown';
            }
        }
        $output .= '<br />';
        $output .= '<b>file:</b> '.@$bt['file'].' - line '.@$bt['line'].'<br />';
        $output .= '<b>call:</b> '.@$bt['class'].@$bt['type'].@$bt['function'].'('.$args.')<br />';
    }
    return $output;
}
+3

- - PHP! , , , . , solomongaby , IDE , Java Objective-C.

Solomongaby, , :

$bt = debug_backtrace();
$end = end($bt);
var_dump($end['class']); //or var_dump($end['file']);
+3

. ( ), ( PHP):

callFunction(1, 2, 3, __FUNCTION__)
callFunction(1, 2, 3, __CLASS__,  __METHOD__)
callFunction(1, 2, 3, $this,  __METHOD__)

  or

$class = new ReflectionClass( __CLASS__ ); 
$method = $class->getMethod( __METHOD__ );
callFunction(1, 2, 3, $method) // $method would be a ReflectionMethod obj

.

  • "", callFunction, .

, , . debug_backtrace ( "" ). .

+1

, , .

0

All Articles