Using Stringable Interface in PHP 8.0

Using Stringable Interface in PHP 8.0

PHP supports magic methods that allow to perform various operations with objects. These methods names starts with two underscores (__). One of these methods is __toString magic method which allows getting an object represented as string. If a class defines the __toString method, then it will be called when an object needs to be treated like a string.

Let's say we have a Cat class which defines the __toString method.

Cat.php

<?php

class Cat
{
    public function __toString(): string
    {
        return 'Meow';
    }
}

Then we create an object of a class and call echo to print an object directly. It will be converted to string via __toString method.

<?php

require_once 'Cat.php';

$cat = new Cat();
echo $cat;

Example will output:

Meow

Since PHP 8.0, every class that defines a __toString magic method automatically implements the Stringable interface. It can be useful for type hinting when strict types are enforced (strict_types=1). For example, we can define a parameter with string|Stringable union type, then it accepts string type or an object of a class that implements the Stringable interface.

In the following example, strict types are enforced. So string|Stringable union type for $str parameter is necessary. If strict types will be removed, then we can declare only string type.

<?php

declare(strict_types=1);

require_once 'Cat.php';

function printSomething(string|Stringable $str) {
    echo $str;
}

printSomething(new Cat());
printSomething('Woof');

If a class defines the __toString method, we can implement the Stringable interface explicitly, but it is not required because this interface is implemented automatically.

<?php

class Dog implements Stringable // To implement this interface is not mandatory
{
    public function __toString(): string
    {
        return 'Woof';
    }
}

The instanceof operator is used to check whether an object is an instance of a class or that class implements an interface. The instanceof operator returns true for classes that defines a __toString method whether this class implements the Stringable interface.

<?php

require_once 'Cat.php';

$cat = new Cat();

echo $cat instanceof Stringable ? 'Yes' : 'No';

Example will output:

Yes

Leave a Comment

Cancel reply

Your email address will not be published.