Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

Stringable

The interface of objects that can be turned into a string.

Syntax

class Name implements Stringable

Return value

stringThe `__toString()` method returns the string form.

Examples

The string|Stringable type in a parameter:

<?php
 
class Email
{
    public function __construct(private string $address) {}
 
    public function __toString(): string
    {
        return $this->address;
    }
}
 
function show(string|Stringable $value): string
{
    return '<' . $value . '>';
}
 
var_dump(new Email('a@example.com') instanceof Stringable);
echo show(new Email('a@example.com'));

Output:

bool(true)
<a@example.com>

Notes

Writing implements Stringable is optional: PHP adds the interface to any class with a __toString() method.

See also

  • strval — Converts a value to a string.
  • JsonSerializable — An interface defining how an object turns into JSON.
  • sprintf — Returns a string built from a format template.

In the tutorial

  • Magic methods — PHP's magic methods — __toString, __get and __set, __call, __invoke and cloning objects.

Thanks for reading!

Donate to the site — we work hard for you.