June 2017
Intermediate to advanced
536 pages
9h 49m
English
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:
<?phpclass 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 ...