This article demonstrates how to convert an object to a string in PHP.

1. Using __toString() magic method

For PHP scalar types, you can use typecasting or strval() function to get their string representation. However, typecasting an object or passing it to strval() will result in a fatal error: ‘Object of class MyClass could not be converted to string’. In order to convert an object to a string, you can override PHP’s default behavior for that class. This can be done by overriding the magic method __toString(), which allows the class to represent the object as a string.

The following example demonstrates this by implementing the __toString() method in a class. Note that the object can now be cast to a string, used with the strval() function, or in the echo statement.

Download  Run Code

You can also use the print_r() function to get the indented string representation of PHP objects, including their protected and private fields, with static class members excluded. To capture the output of the print_r() function in a string instead of printing it, you can set the second parameter to true.

Download  Run Code

3. Using var_export() function

Alternatively, you can use the var_export() function to get the parsable and indented string representation of an object. When the second parameter to var_export() is set to true, it returns a string representation of the object rather than outputting it. Note that the returned string is valid PHP code and includes all public, protected, and private members of the object. However, var_export() does not handle circular references, as you cannot generate parsable PHP code for it.

Download  Run Code

4. Using var_dump() function

For debugging purposes, you may want to use the var_dump() function, which recursively displays structured information about the object, including the type and value of all its public, private, and protected properties. It is possible to capture the indented output of the var_dump() function to a string variable using output-control functions, as shown below:

Download  Run Code

5. Using serialize() function

It is worth noting that you can convert objects to strings for storage without losing their type or structure. This technique is known as serialization, and can be done using the serialize() function. To reconstruct the serialized string back to the object again, you can use the unserialize() function.

Download  Run Code

 
Also See:

PHP equivalent of Java’s toString() method

That’s all there is to converting an object to a string in PHP.