Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / PHP

Stringable

Označí objekt poskytujúci text cez __toString.

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

Syntax

public function __toString(): string

Označí objekt poskytujúci text cez __toString. V PHP 8 deklarácia metódy automaticky znamená Stringable. Bežný reťazec takým objektom nie je. Únia string a Stringable prijme oba aj pri striktnom typovaní.

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]

Príklady

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

Výsledok

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

Zdroje