Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

PHP equivalent of .NET/Java's toString()

How would I change the value of a PHP variable over to string?

I was searching for an option that could be better compared to connecting with an empty string:

$myText = $myVar . '';


Like the ToString() method in Java or .NET.
by

2 Answers

akshay1995
Use print_r:

$myText = print_r($myVar,true);

You can also use it like:

$myText = print_r($myVar,true)."foo bar";

This will set $myText to a string, like:

array (
0 => '11',
)foo bar
Use var_export to get a little bit more info (with types of variable,...):

$myText = var_export($myVar,true);
sandhya6gczb
This is done with typecasting:

$strvar = (string) $var; // Casts to string
echo $var; // Will cast to string implicitly
var_dump($var); // Will show the true type of the variable

In a class you can define what is output by using the magical method __toString. An example is below:

class trees {
public function __toString()
{
return 'Fifty five trees';
}
}

$ex = new trees;
var_dump($ex, (string) $ex);
// Returns: instance of trees and "fifty five trees"

Login / Signup to Answer the Question.