Page 1 of 1
convert variables to strings
Posted: Tue Dec 21, 2004 2:41 am
by tores
Hi
How can I achieve the same effect in PHP as with Python's str-function? That is, convert a variable (e.g. $var) to its equivalent string representation ("var").
Regards tores
Posted: Tue Dec 21, 2004 2:59 am
by vietnamese
use (string) if variable is number type, datetime...
sample
$temp = 123456;
$temp = (string) $temp;
however variable is array, you can use function serialize($array) to convert a array to string, and convert that string to array, use function unserialize($string)
Posted: Tue Dec 21, 2004 3:20 am
by tores
Sorry for not beeing spesific. I don't want to convert the variable's contents to a string. It's the variable-name itself I want to convert. The reason for this is that when dumping a variable I also want the variable's name printed out...
Regards tores
Posted: Tue Dec 21, 2004 3:45 am
by vietnamese
he he !! if you want print name of $value, you use echo "value"; when you use a variable, you must know variable's name so that, you can create a avariable contant that name string.
I don't understand why you need dumping a avariable as a string??
can you show me??
Posted: Tue Dec 21, 2004 3:58 am
by tores
okey... This is exactly what I want...
I have this small function:
Code: Select all
<?php
function dump($var){
echo "DEBUG: ";
var_dump($var);
echo "<br>";
}
?>
This function just prints "DEBUG: <value of $var>"... This way I have to look at the value printed to figure out which variable is dumped (if I use this function in several places)... It would be a lot easier if I could print something like "DEBUG: <name of $var> <value of $var>". <name of $var> should then refer to the name of the parameter used when calling dump... Maybe this is impossible without specifying another parameter like
dump($var_value, $var_name)? If not, I would like to know...
regards tores
Posted: Tue Dec 21, 2004 10:35 am
by rehfeld
i understand exactly what you mean.
unfortunately i think you will need to modify the function like you suggested
dump('$foo', $foo);
this limitations comes from putting this into a function. the variable loses its "name" inside the scope of a function, only the value is passed.
but this should work for variables in the global scope, but wont really work w/ nested variables
maybe you could play around w/ eval() to make it work w/ a greater range of variables, or, just pass 2 parameters to your origional function
Code: Select all
$foo = 'bar';
function dump($var) {
echo '$' . $var . ' => ';
var_dump($GLOBALS[$var]);
}
dump('foo');
Posted: Tue Dec 21, 2004 12:13 pm
by timvw
or play around with variable variables
[php_man]variables.variable[/php_man]