The __toString Method

The __toString method is a magic method in PHP that defines how an object should behave when an attempt is made to convert it to a string. This method is automatically called when the object is used in a context where a string is expected, for example, when outputting via echo or during concatenation. The method must return a string representation of the object.

Syntax

phppublic function __toString(): string
{
  // return string representation
}

Example

Let's create a simple class with the __toString method:

php<?php
  class User
  {
    public function __toString(): string
    {
      return 'User object';
    }
  }

  $user = new User();
  echo $user;
?>

Code execution result:

php'User object'

Example

A more complex example returning object properties:

php<?php
  class Product
  {
    private $name = 'Laptop';
    private $price = 1000;

    public function __toString(): string
    {
      return $this->name . ' - 
 . $this->price;
    }
  }

  $product = new Product();
  echo 'Product: ' . $product;
?>

Code execution result:

php'Product: Laptop - $1000'

See Also

  • the __construct method,
    which is the object constructor
  • the __destruct method,
    which is the object destructor