PHP Gets in which file the specified function is defined and the line number instance it is in

  • 2021-06-28 08:57:10
  • OfStack

When debugging open source code, you want to see the definition of a function, so you need to locate it.You can automatically prompt for this in an IDE like zend studio, but what can we do if such a development tool is not installed?Refer to the following code, which may contain what you need.


<?php
function a() {
}
class b {
    public function f() {
    }
}
function function_dump($funcname) {
    try {
        if(is_array($funcname)) {
            $func = new ReflectionMethod($funcname[0], $funcname[1]);
            $funcname = $funcname[1];
        } else {
            $func = new ReflectionFunction($funcname);
        }
    } catch (ReflectionException $e) {
        echo $e->getMessage();
        return;
    }
    $start = $func->getStartLine() - 1;
    $end =  $func->getEndLine() - 1;
    $filename = $func->getFileName();
    echo "function $funcname defined by $filename($start - $end)\n";
}
function_dump('a');
function_dump(array('b', 'f'));
$b = new b();
function_dump(array($b, 'f'));
?>


Related articles: