CKTIS / PHP
Stringable
Marque un objet fournissant du texte par __toString.
Version : PHP 8.4; repository runtime, production runtime not attested
Syntaxe
public function __toString(): stringMarque un objet fournissant du texte par __toString. En PHP 8 cette méthode implique automatiquement Stringable. Une chaîne native n’est pas un tel objet. Une union de string et Stringable accepte les deux même en mode strict.
declare(strict_types=1);
class Tag {public function __toString(): string{return "label";}}
function render(string|Stringable $x): string{return (string)$x;}
$t=new Tag(); echo json_encode([$t instanceof Stringable,render($t),render("raw"),is_string($t)]);
[true,"label","raw",false]
Exemples
<?php
declare(strict_types=1);
class Tag {public function __toString(): string{return "label";}}
function render(string|Stringable $x): string{return (string)$x;}
$t=new Tag(); echo json_encode([$t instanceof Stringable,render($t),render("raw"),is_string($t)]);
Résultat
[true,"label","raw",false]