Is there a way to get the name of a variable? PHP - Reflection

前端 未结 11 586
旧巷少年郎
旧巷少年郎 2020-12-15 08:50

I know this is not exactly reflection, but kind of. I want to make a debug function that gets a variable and prints a var_dump and the variable name.

Of course, when

11条回答
  •  时光说笑
    2020-12-15 09:28

    I know this is very very late, but i did it in a different way.

    It might honestly be a bit bad for performance, but since it's for debugging it shouldn't be a problem.

    I read the file where the function is called, on the line it was called and I cut out the variable name.

    function dump($str){
        // Get the caller with debug backtrace
        $bt = debug_backtrace();
        $caller = array_shift($bt);
    
        // Put the file where the function was called in an array, split by lines
        $readFileStr = file($caller['file']);
    
        // Read the specific line where the function was called
        $lineStr = $readFileStr[$caller['line'] -1];
    
        // Get the variable name (including $) by taking the string between '(' and ')'
        $regularOutput = preg_match('/\((.*?)\)/', $lineStr, $output);
        $variableName = $output[1];
    
        // echo the var name and in which file and line it was called
        echo "var: " . $variableName . " dumped in file: " . $caller['file'] . ' on line: ' . $caller['line'] . '
    '; // dump the given variable echo '
    ' . var_export($str, true) . '
    '; }

提交回复
热议问题