CKTIS / PHP
Stringable
Marca un oggetto che fornisce testo tramite __toString.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
public function __toString(): stringMarca un oggetto che fornisce testo tramite __toString. In PHP 8 dichiarare il metodo comporta Stringable implicitamente. Una stringa nativa non è tale oggetto. L’unione di string e Stringable ammette entrambi anche in modalità rigorosa.
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]
Esempi
<?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)]);
Risultato
[true,"label","raw",false]