Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / PHP

Stringable

Oznacza obiekt zwracający tekst przez __toString.

Wersja: PHP 8.4; repository runtime, production runtime not attested

Składnia

public function __toString(): string

Oznacza obiekt zwracający tekst przez __toString. W PHP 8 sama deklaracja tej metody niejawnie implementuje Stringable. Zwykły napis nie jest takim obiektem. Unia string ze Stringable dopuszcza oba, również przy ścisłym typowaniu.

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]

Przykłady

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

Wynik

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

Źródła