array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'fr', ), 'this' => array ( 0 => 'class.stringable.php', 1 => 'Stringable', ), 'up' => array ( 0 => 'reserved.interfaces.php', 1 => 'Interfaces et Classes Prédéfinies', ), 'prev' => array ( 0 => 'weakmap.offsetunset.php', 1 => 'WeakMap::offsetUnset', ), 'next' => array ( 0 => 'stringable.tostring.php', 1 => 'Stringable::__toString', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'fr', 'path' => 'language/predefined/stringable.xml', ), 'extra_header_links' => array ( 'rel' => 'alternate', 'href' => '/manual/en/feeds/class.stringable.atom', 'type' => 'application/atom+xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 8)
L'interface Stringable désigne une classe possédant une méthode __toString(). Contrairement à la plupart des interfaces, Stringable est implicitement présente sur toute classe pour laquelle la méthode magique __toString() est définie, et ce bien qu'elle puisse et devrait être déclarée explicitement.
Sa valeur principale est de permettre aux fonctions de vérifier le type par rapport
au type d'union string|Stringable
pour accepter soit une chaîne de caractères primitive,
soit un objet pouvant être transtypé en chaîne de caractères.
Exemple #1 Exemple simple
<?php
class IPv4Address implements Stringable {
private string $oct1;
private string $oct2;
private string $oct3;
private string $oct4;
public function __construct(string $oct1, string $oct2, string $oct3, string $oct4) {
$this->oct1 = $oct1;
$this->oct2 = $oct2;
$this->oct3 = $oct3;
$this->oct4 = $oct4;
}
public function __toString(): string {
return "$this->oct1.$this->oct2.$this->oct3.$this->oct4";
}
}
function showStuff(string|Stringable $value) {
// Un Stringable sera converti en chaîne de caractères ici en appelant
// __toString.
print $value;
}
$ip = new IPv4Address('123', '234', '42', '9');
showStuff($ip);
?>
Résultat de l'exemple ci-dessus est similaire à :
123.234.42.9