Using __toString()
The __toString()
magic method triggers when we use an object in a string context. It allows us to decide how the object will react when it is treated like a string.
Let's take a look at the following example:
<?php class User { protected $name; protected $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $user = new User('John', 34); echo $user;
Here, we have a simple User
class that accepts the $name
and $age
parameters through its constructor method. Other than that, there is nothing else to indicate how the class should respond to the attempt of using it in the string context, which is exactly what we are doing right after the class declaration, as we are trying to echo
 the object instance itself.
In its current form, the resulting output would be as follows:
Catchable fatal error: Object of class User could not be converted to string in...
The __toString()
magic method allows us to circumvent this error...