tree em
tree em

Reputation: 21781

convert $var of function to string?

My goal just debug

  function dbg($var){
       echo "you have passed $var";
    }

call dbg($test)

output:
      you have passed test

call dbg("var")

output:
      you have passed "var"

In php .anyone could help me to do that?

Upvotes: 0

Views: 199

Answers (2)

Spudley
Spudley

Reputation: 168853

Well, the second case is fairly straightforward - you're passing a string and you want to display the string. No worries.

But for the first case, I'm afraid the answer is: No you can't.

Once inside the function, PHP doesn't know anything about the variable that was passed into it other than the value.

I can't really see that it would be of much value though. It would be trivial to change your code to pass in a name and a value -- ie something like this:

function dbg($name,$value) {
    print "You passed $name, and the value was $value";
}

dbg('test',$test);

That's not really all that great either though -- you may as well just use print_r() and friends.

If you really want more powerful debugging tools, you should look into xDebug. It's a proper debugging tool for PHP, which allows you to step through the code line-by-line, and see the contents of variables at any point during the program run (among many other good features). It also integrates nicely with several popular IDEs.

Upvotes: 1

Naftali
Naftali

Reputation: 146360

Try this if $var is a global variable:

   function dbg($var){
       echo "you have passed {$GLOBALS[$var]}";
    }

Upvotes: 2

Related Questions