Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

Stringable

Marca um objeto que fornece texto por __toString.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

public function __toString(): string

Marca um objeto que fornece texto por __toString. No PHP 8 declarar o método implica Stringable automaticamente. Uma cadeia nativa não é esse objeto. A união de string e Stringable admite ambos mesmo em modo estrito.

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]

Exemplos

<?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)]);

Resultado

[true,"label","raw",false]

Fontes