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.
interface Stringable { public function __toString(): string; }
Try it
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.
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
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 Stringabledocuments the intent and works the same way. - Plain strings are not
Stringable."abc" instanceof Stringableisfalse; that is why the unionstring|Stringableis needed. - Built-in classes. All exceptions (through
Throwable) areStringable; so are several others such asSplFileInfo. - Implicit conversion. In string contexts (
echo, concatenation,strlen(),implode(), comparison with strings) PHP calls__toString(). Withdeclare(strict_types=1)passing an object where astringparameter is declared is still aTypeError; 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
Stringablethrough__toString(), because enums may not define it. - Interfaces can extend it.
interface Money extends Stringableforces implementers to provide a string form.