← Back to Chapters

PHP OOP __toString() Method

? PHP OOP __toString() Method

✨ Quick Overview

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.

? Key Concepts

  • Automatically called when an object is converted to a string
  • Must always return a string value
  • Improves debugging and readability
  • Commonly used in logging and display logic

? Syntax & Theory

The __toString() method is declared inside a class and must return a string. PHP throws a fatal error if any other type is returned.

? View Code Example
// 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()
?>

? Live Output / Explanation

When the object $book is echoed, PHP automatically calls __toString() and outputs:

Book: PHP for Beginners by Meghraj

? Interactive Concept

Try concatenating the object with a string:

"Reading: " . $book — PHP still calls __toString() automatically.

? Use Cases

  • Logging object data
  • Displaying user-friendly object summaries
  • Debugging complex objects
  • Readable output in templates

✅ Tips & Best Practices

  • Always return a string from __toString()
  • Keep logic minimal inside this method
  • Use for presentation, not business logic

? Try It Yourself

  • Create a Car class with brand and model
  • Implement __toString()
  • Echo multiple objects
  • Concatenate objects with strings