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

前端 未结 5 914
花落未央
花落未央 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 05:11

    If it is a simple script, where all variables are defined in the global scope, you could get for the $GLOBALS solution:

    function my_dump($a){
        if(is_string($a) and isset($GLOBALS[$a])) {
            echo "varname: $a\n";
            $a=&$GLOBALS[$a];
        }
        echo '
    '.$name.":\n";
        var_export($a);
        echo '
    '; }

    this way you can call the dump function with the variable name instead

    my_dump("cool_variable_name");
    

    instead of

    my_dump($cool_variable_name);
    

提交回复
热议问题