CKTIS / PHP
Stringable
Mark an object that can supply a string representation through __toString.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __toString(): stringMark an object that can supply a string representation through __toString. PHP 8 implicitly implements Stringable when a class defines that method. A native string is not a Stringable object. Use a string-or-Stringable union to admit both, including in strict callers.
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]
Examples
<?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)]);
Result
[true,"label","raw",false]