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.
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.
PHP is dynamically typed, so like Chris Fournier said, "If you use it like a string it becomes a string". If you're looking for more control over the format of the string then printf is your answer.
Putting it in double quotes should work:
For objects, you may not be able to use the cast operator. Instead, I use the
json_encode()
method.For example, the following will output contents to the error log:
Some if not all of the methods above fail when the intended string variable has a leading zero ie 077543 an attempt to convert such a variable fails to get the intended string because the variable is converted to base 8 (octal).
All these will make
$str
have a value of 32611In addition to the answer given by Thomas G. Mayfield:
If you follow the link to the string casting manual, there is a special case which is quite important to understand:
(string) cast is preferable especially if your variable $a is an object, because PHP will follow the casting protocol according to its object model by calling __toString() magic method (if such is defined in the class of which $a is instantiated from).
PHP does something similar to
The (string) casting operation is a recommended technique for PHP5+ programming making code more Object-Oriented. IMO this is a nice example of design similarity (difference) to other OOP languages like Java/C#/etc., i.e. in its own special PHP way (whenever it's for the good or for the worth).
You can use also, var_export php function.