CKTIS / PHP
__toString
Javna metoda `__toString` zagotovi niz za echo, stik nizov ali izrecno pretvorbo.
Različica: PHP 8.4; repository runtime, production runtime not attested
Sintaksa
public function __toString(): stringJavna metoda __toString zagotovi niz za echo, stik nizov ali izrecno pretvorbo. V PHP 8 razred s tem implementira Stringable. Pri strict_types zahteva parameter tipa string izrecno pretvorbo objekta. Metoda lahko sproži izjemo.
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
Primeri
<?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); }
Rezultat
[true,"T-4"] TypeError