CKTIS / PHP
__toString
La méthode publique `__toString` fournit le texte pour echo, la concaténation ou une conversion explicite.
Version : PHP 8.4; repository runtime, production runtime not attested
Syntaxe
public function __toString(): stringLa méthode publique __toString fournit le texte pour echo, la concaténation ou une conversion explicite. En PHP 8 sa présence implique Stringable. Avec strict_types, convertir explicitement l’objet est nécessaire pour un paramètre de type string. La méthode peut lever une 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
Exemples
<?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); }
Résultat
[true,"T-4"] TypeError