The __toString() magic method in PHP defines how an object behaves when it is treated as a string. It is automatically invoked during echo, print, or string concatenation.
The __toString() method is declared inside a class and must return a string. PHP throws a fatal error if any other type is returned.
// Demonstrating __toString() magic method
<?php
class Book {
private $title;
private $author;
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}
public function __toString() {
return "Book: " . $this->title . " by " . $this->author;
}
}
$book = new Book("PHP for Beginners", "Meghraj");
echo $book; // Automatically calls __toString()
?>
When the object $book is echoed, PHP automatically calls __toString() and outputs:
Book: PHP for Beginners by Meghraj
Try concatenating the object with a string:
"Reading: " . $book — PHP still calls __toString() automatically.
__toString()Car class with brand and model__toString()