CKTIS / PHP
__toString
De openbare methode `__toString` levert tekst voor echo, samenvoegen of expliciete conversie.
Versie: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __toString(): stringDe openbare methode __toString levert tekst voor echo, samenvoegen of expliciete conversie. Vanaf PHP 8 implementeert de klasse daarmee Stringable. Onder strict_types vereist een parameter van alleen type string een expliciete conversie van het object. De methode mag een uitzondering opwerpen.
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
Voorbeelden
<?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); }
Resultaat
[true,"T-4"] TypeError