Using Stringable Interface in PHP 8.0

PHP supports magic methods that allows to perform various operations with objects. These methods names starts with two underscores (__). One of these methods is __toString magic method which allows to get an object represented as string. If class defines a __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 __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 Stringable interface. It can useful for type hinting when strict types are enforced (strict_types=1). For example, we can define parameter with string|Stringable union type, then it accepts string type or an object of a class that implements 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 a __toString method we can implement 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 or not this class implements Stringable interface.

<?php

require_once 'Cat.php';

$cat = new Cat();

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

Example will output:

Yes

Leave a Comment

Your email address will not be published. Required fields are marked *