Skip to content

Stringable

What a class adds so that its objects can be written as text.

A class that implements Stringable declares one method, toString(), returning the text its objects should appear as. From then on echo, joining with ., a value inside "{...}", and an as string conversion all call it, so you hand the object itself to anything that builds a line of text instead of keeping a second field beside it. A function can also ask for Stringable rather than a class name, which means "anything that can be written as text".

Good to know: a class without toString() is refused where it is rendered, and the message names Stringable as the fix. The method has no special spelling — it is toString, not __toString — so you may also call it by name like any other method.

Examples

A log line built from objects

<?nvs
// A class can say how it looks as text by adding `toString()`. After that you
// hand the object itself to anything that writes a line, and every line is
// built the same way.
class AuditEntry implements Stringable
{
public string $what;
public function constructor(string $what)
{
$this->what = $what;
}
public function toString(): string
{
return $this->what;
}
}
// A kind of entry that needs the user in the line. It does not repeat
// `implements Stringable`, because it already has that from `AuditEntry`.
final class LoginFailed extends AuditEntry
{
public string $user;
public function constructor(string $user)
{
$this->user = $user;
parent::constructor('login failed');
}
public function toString(): string
{
return 'login failed for ' . $this->user;
}
}
final class Audit
{
// The parameter asks for anything that can be written as text. Any class
// with `toString()` fits, and none of them needs to know about this one.
public static function write(Stringable $entry): void
{
echo "[audit] {$entry}\n";
}
}
Audit::write(new AuditEntry('cart emptied'));
Audit::write(new LoginFailed('ada'));
// The object also joins straight into a longer message.
var $failed = new LoginFailed('bob');
echo 'the last problem was: ' . $failed . "\n";
// One list holding both classes. Every entry is written the same way.
array<Stringable> $recent = [new AuditEntry('order placed'), new LoginFailed('cho')];
foreach ($recent as Stringable $entry) {
echo '- ', $entry, "\n";
}
Output
[audit] cart emptied
[audit] login failed for ada
the last problem was: login failed for bob
- order placed
- login failed for cho