How can I find out the name of a variable inside a function?

前端 未结 5 915
花落未央
花落未央 2021-01-21 04:46

I have a function

function my_dump($a,$name){
    echo \'
\'.$name.\":\\n\";
    var_export($a);
    echo \'
\'; }

How can

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 04:57

    If you need to debug code, then using tools like xdebug is a lot more flexible and efficient than homebrew variable dumps; but debug_backtrace() (although a big overhead) might give you what you need. Extract the filename and line number of the call to your debug dump function, and parse that line to extract the variable name that's used when calling the function

    function my_dump($a) {
        $backtrace = debug_backtrace()[0];
        $fh = fopen($backtrace['file'], 'r');
        $line = 0;
        while (++$line <= $backtrace['line']) {
            $code = fgets($fh);
        }
        fclose($fh);
        preg_match('/' . __FUNCTION__ . '\s*\((.*)\)\s*;/u', $code, $name);
        echo '
    '.trim($name[1]).":\n";
        var_export($a);
        echo '
    '; } $foo = 'bar'; $baz = array( 'Hello', 'World' ); my_dump($foo); my_dump( $baz );

    If your PHP version doesn't support array dereferencing, change

    $backtrace = debug_backtrace()[0];
    

    to

    $backtrace = debug_backtrace();
    $backtrace = $backtrace[0];
    

    If your call to my_dump() spans multiple lines (like my $baz example), you'll need a slightly more sophisticated parser to extract the variable name from your code.

提交回复
热议问题