CKTIS / PHP
__toString
Define public `__toString` to supply a string representation during echo, concatenation or an explicit cast.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __toString(): stringDefine public __toString to supply a string representation during echo, concatenation or an explicit cast. In PHP 8 an object with this method implicitly implements Stringable. Under strict_types a string-only parameter still rejects the object unless explicitly cast, whereas a Stringable parameter can accept it. The method can throw an exception.
declare(strict_types=1);
class Ticket {
public function __construct(private int $id) {}
public function __toString(): string { return "T-" . $this->id; }
}
function label(string $s): string { return $s; }
$t = new Ticket(4);
echo json_encode([$t instanceof Stringable, label((string)$t)]), PHP_EOL;
try { label($t); } catch (TypeError $e) { echo get_class($e); }
[true,"T-4"]
TypeError
Examples
<?php
declare(strict_types=1);
class Ticket {
public function __construct(private int $id) {}
public function __toString(): string { return "T-" . $this->id; }
}
function label(string $s): string { return $s; }
$t = new Ticket(4);
echo json_encode([$t instanceof Stringable, label((string)$t)]), PHP_EOL;
try { label($t); } catch (TypeError $e) { echo get_class($e); }
Result
[true,"T-4"] TypeError