PHP将变量名放在一个字符串中


PHP put the variable name in a string

我有一个在屏幕上转储变量的函数,我想做的是在变量的值旁边显示变量的名称,这样它就会输出这样的东西:

function my_function($var) {
    return '<pre>' . var_dump($var) . '</pre>';
}
$myVar = 'This is a variable';
echo my_function($var); // outputs on screen: myVar has value: This is a variable
$anotherVar = 'Something else';
echo my_function($anotherVar); // outputs on screen: anotherVar has value: Something else

我该怎么做?

PHP没有提供简单的方法。PHP开发人员从来没有看到任何理由认为这是必要的。

但是,您可以使用以下几种解决方法:有没有一种方法可以获得变量的名称?PHP-反射和这里:如何在PHP中获得作为字符串的变量名?

在这种情况下,debug_backtrace()函数可能是最有效的:

function my_function($var) {
    $caller = debug_backtrace()[0];
    $file = $caller['file'];
    $lineno = $caller['line'];
    $fp = fopen($file, 'r');
    $line = "";
    for ($i = 0; $i < $lineno; $i++) {
        $line = fgets($fp);
    }
    $regex = '/'.__FUNCTION__.''(([^)]*)')/';
    preg_match($regex, $line, $matches);
    echo '<pre>'. $matches[1]. ": $var</pre>";
}

$anotherVar = 'Something else';
my_function($anotherVar);
// output: $anotherVar: Something else