CKTIS / PHP
__toString
Verejná metóda `__toString` poskytne reťazec pre echo, zreťazenie alebo výslovné pretypovanie.
Verzia: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __toString(): stringVerejná metóda __toString poskytne reťazec pre echo, zreťazenie alebo výslovné pretypovanie. V PHP 8 tým trieda implementuje Stringable. Pri strict_types vyžaduje parameter typu string výslovné pretypovanie objektu. Metóda môže vyhodiť výnimku.
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
Príklady
<?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); }
Výsledok
[true,"T-4"] TypeError