0

I have a function for dumping variables on the screen and what I'd like to do is to show the name of the variable next to the value of the variable, so it would output something like this:

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

How can I do this ?

ltdev
  • 4,037
  • 20
  • 69
  • 129
  • What is the content of the function `my_function()`? – Ben Jan 12 '16 at 10:55
  • 2
    Possible duplicate of [How to get a variable name as a string in PHP?](http://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php) – Ben Jan 12 '16 at 10:55
  • Did an update, please review – ltdev Jan 12 '16 at 10:56
  • `echo my_function($var);` should this be : `echo my_function($myVar);` ? – Alex Jan 12 '16 at 10:58
  • 1
    Why not simply use a second argument for variable name. `my_function($variable, $var_name)` – Sougata Bose Jan 12 '16 at 10:59
  • @Sougata: I currently pass as a second argument the name as a string, so the function is basically like this: `my_function($var, $label = '')`.. I'm just wondering whether there's a quicker way to output the result without having to pass the variable name manually – ltdev Jan 12 '16 at 11:02
  • Passing the second argument would be less costly I think than other procedures. – Sougata Bose Jan 12 '16 at 11:06
  • if this is for debugging purposes, I usually do one place at a time else its often overlook the place and become messy in the view – Andrew Jan 12 '16 at 11:13

2 Answers2

0

PHP offers no simple way of doing this. The PHP developers never saw any reason why this should be neccesary.

You can however use a couple of workarounds found here: Is there a way to get the name of a variable? PHP - Reflection and here: How to get a variable name as a string in PHP?

Community
  • 1
  • 1
AgeDeO
  • 3,137
  • 2
  • 25
  • 57
0

Probably, debug_backtrace() function in such case will be the most effective:

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
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105