How to get a variable name as a string in PHP?

前端 未结 24 1963
南旧
南旧 2020-11-22 01:35

Say i have this PHP code:

$FooBar = \"a string\";

i then need a function like this:

print_var_name($FooBar);
24条回答
  •  天命终不由人
    2020-11-22 02:01

    This is exactly what you want - its a ready to use "copy and drop in" function that echo the name of a given var:

    function print_var_name(){
        // read backtrace
        $bt   = debug_backtrace();
        // read file
        $file = file($bt[0]['file']);
        // select exact print_var_name($varname) line
        $src  = $file[$bt[0]['line']-1];
        // search pattern
        $pat = '#(.*)'.__FUNCTION__.' *?\( *?(.*) *?\)(.*)#i';
        // extract $varname from match no 2
        $var  = preg_replace($pat, '$2', $src);
        // print to browser
        echo trim($var);
    }
    

    USAGE: print_var_name($FooBar)

    PRINT: FooBar

    HINT Now you can rename the function and it will still work and also use the function several times in one line! Thanks to @Cliffordlife

提交回复
热议问题