This article demonstrates the PHP equivalent of Java’s toString() method.

1. Using Typecasting or strval() function

You can use type casting to get the string representation of the scalar types (int, float, string, or bool). To cast a variable to a string, you can enclose the string type within parentheses before the variable.

The following code demonstrates the type conversion from scalar types (and null) to strings. It is worth noting that the boolean values true and false are converted to the "1" and "" (the empty string), respectively. The null value, when cast to a string, results in an empty string. The program uses var_dump() to display the type and value of the converted variable.

Download  Run Code

 
Currently, (binary) is an alias for the (string) cast. However, this should be used with caution, as its behavior may change in the future. It is also possible to enclose the variable in double quotes, rather than casting it to a string. This technique is called variable interpolation in PHP, resulting in compact, readable, and cleaner code. For example,

Download  Run Code

 
Alternatively, you can use the strval() function to convert a value to a string, which works in a similar way as the (string) cast.

Download  Run Code

2. Using __toString() Magic Method

Passing an array to the strval() function will result in the PHP warning ‘Array to string conversion’. Objects, on the other hand, produce the fatal error message ‘Object of class classname could not be converted to string’. To convert objects to strings, you can have the class override the magic method __toString() and return a value capturing all fields of the object. For example,

Download  Run Code

The print_r() function prints human-readable information about a variable. It can return a string instead of outputting it when the second parameter is set to true. The print_r() function will also work with objects and arrays, and their string representation contains values presented in a format showing keys and elements.

Download  Run Code

4. Using var_export() function

Finally, you can use the var_export() function to output the parsable string representation of a scalar variable, an array, or an object. To return the string representation instead, you can set the second parameter of var_export() to true.

Note that unlike typecasting, strval(), and print_r() function, the var_export() function converts the boolean values true and false to their string equivalent "true" and "false" respectively. Similary, the null values gets converted to string "NULL".

Download  Run Code

 
Also See:

Convert an object to a string in PHP

That’s all about PHP the equivalent of Java’s toString() method.