What is Stringable Interface in PHP 8?

In PHP 8, a new Stringable interface is added that works with the __toString() magic method. The __toString method allows an object to be represented as a string. When a class defines this method, PHP automatically implements the Stringable interface, enabling better type hinting and string conversion handling.

Syntax

interface Stringable
{
    public function __toString(): string;
}

Basic Example

Here's how to implement the __toString method in a class −

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

$employee = new Employee();
echo (string)$employee;
?>
Employee Name

Automatic Stringable Implementation

In PHP 8, any class that implements __toString automatically implements the Stringable interface without explicit declaration −

<?php
declare(strict_types=1);

class Employee {
    public function __toString(): string {
        return 'Employee Details';
    }
}

$emp = new Employee();
var_dump($emp instanceof Stringable);
?>
bool(true)

Type Hinting with Stringable

The Stringable interface is particularly useful for type hinting when you want to accept both strings and objects that can be converted to strings −

<?php
class Product {
    private string $name;
    
    public function __construct(string $name) {
        $this->name = $name;
    }
    
    public function __toString(): string {
        return $this->name;
    }
}

function displayMessage(string|Stringable $message): void {
    echo "Message: " . $message;
}

$product = new Product("Laptop");
displayMessage($product);
displayMessage(" - Available");
?>
Message: Laptop
Message:  - Available

Key Benefits

  • Automatic Implementation: No need to explicitly implement the interface
  • Type Safety: Better type hinting with strict types enabled
  • Union Types: Combine with string type for flexible parameters
  • Backward Compatibility: Works seamlessly with existing __toString implementations

Conclusion

The Stringable interface in PHP 8 enhances type safety and provides better string handling capabilities. It automatically applies to classes with __toString methods, making type hinting more flexible and precise.

Updated on: 2026-03-15T09:43:05+05:30

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements