Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / PHP

Stringable

Označí objekt poskytující text přes __toString.

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

Syntaxe

public function __toString(): string

Označí objekt poskytující text přes __toString. V PHP 8 deklarace metody automaticky znamená Stringable. Běžný řetězec takovým objektem není. Unie string a Stringable přijme oba i při přísném typování.

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]

Pří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ýsledek

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

Zdroje