0
0
PHPprogramming~5 mins

__toString for string representation in PHP

Choose your learning style9 modes available
Introduction

The __toString method lets you decide how an object turns into a string. This helps when you want to print or show an object in a simple way.

When you want to print an object directly with <code>echo</code> or <code>print</code>.
When you want to convert an object to a string for logging or debugging.
When you want to customize how an object looks as text in messages or UI.
When you want to avoid errors from printing objects without string form.
Syntax
PHP
public function __toString(): string {
    // return a string representation of the object
}

The method must be public and return a string.

It is called automatically when the object is used as a string.

Examples
This example shows a Person class that returns the person's name when printed.
PHP
<?php
class Person {
    private string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
    public function __toString(): string {
        return "Person: " . $this->name;
    }
}

$p = new Person("Anna");
echo $p;
This example shows a Product class that returns a string with the product title and price.
PHP
<?php
class Product {
    private string $title;
    private float $price;
    public function __construct(string $title, float $price) {
        $this->title = $title;
        $this->price = $price;
    }
    public function __toString(): string {
        return "$this->title costs {$this->price}";
    }
}

$product = new Product("Book", 12.99);
echo $product;
Sample Program

This program creates a Car object and prints it. The __toString method defines how the car looks as a string.

PHP
<?php
class Car {
    private string $make;
    private string $model;

    public function __construct(string $make, string $model) {
        $this->make = $make;
        $this->model = $model;
    }

    public function __toString(): string {
        return "Car: $this->make $this->model";
    }
}

$car = new Car("Toyota", "Corolla");
echo $car;
OutputSuccess
Important Notes

If you try to print an object without __toString, PHP will give an error.

Use __toString to make objects easier to read and debug.

Summary

__toString lets you control how an object turns into a string.

It is called automatically when printing or converting an object to string.

Always return a string from __toString.