ToString() equivalent in PHP
How do I convert the value of a PHP variable to string?
I was looking for something better than concatenating with an empty string:
$myText = $myVar . '';
Like the ToString()
method in Java or .NET.
You can use the casting operators:
$myText = (string)$myVar;
There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls.
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 Bottles {
public function __toString()
{
return 'Ninety nine green bottles';
}
}
$ex = new Bottles;
var_dump($ex, (string) $ex);
// Returns: instance of Bottles and "Ninety nine green bottles"
Some more type casting examples:
$i = 1;
// int 1
var_dump((int) $i);
// bool true
var_dump((bool) $i);
// string "1"
var_dump((string) 1);
Use print_r :
$myText = print_r($myVar,true);
You can also use 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);
链接地址: http://www.djcxy.com/p/86616.html
上一篇: 在PHP中将整数转换为字符串
下一篇: 在PHP中相当于ToString()