Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Functions and Classes

The Stringable interface

Reference for the PHP Stringable interface: automatic implementation of __toString(), string|Stringable types, instanceof checks and common pitfalls.

Stringable is a built-in interface (PHP 8.0) with a single method, __toString(): string. Any class that declares __toString() implements Stringable automatically, even without writing implements Stringable.

Its main use is in type declarations. A parameter typed string|Stringable accepts both plain strings and objects that can be turned into strings, and $value instanceof Stringable tells you whether an object has a string form.

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

Try it

PHP Automatic implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Accepting string|Stringable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
class Name implements Stringable
{
    public function __toString(): string { /* return a string */ }
}

function f(string|Stringable $value) {}
Part Description
__toString() Takes no arguments and must return a string.
Return type Since PHP 8.0 __toString() gets an implicit : string return type even if you omit it.

Errors: an object without __toString() used as a string throws Error ("Object of class X could not be converted to string"). Since PHP 7.4 __toString() may throw exceptions.

Usage notes

  • Automatic, but explicit is clearer. Writing implements Stringable documents the intent and works the same way.
  • Plain strings are not Stringable. "abc" instanceof Stringable is false; that is why the union string|Stringable is needed.
  • Built-in classes. All exceptions (through Throwable) are Stringable; so are several others such as SplFileInfo.
  • Implicit conversion. In string contexts (echo, concatenation, strlen(), implode(), comparison with strings) PHP calls __toString(). With declare(strict_types=1) passing an object where a string parameter is declared is still a TypeError; cast it with (string) first.
  • Do not hide heavy work or side effects in __toString(); it may be called in places you do not expect, such as logging.
  • Enums cannot implement Stringable through __toString(), because enums may not define it.
  • Interfaces can extend it. interface Money extends Stringable forces implementers to provide a string form.