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

CKTIS / PHP

Typový systém a deklarace

Typové deklarace kontrolují argumenty, výsledky a vlastnosti.

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

Syntaxe

declare(strict_types=1); function code(int|string $v): string { /* ... */ }

Typové deklarace kontrolují argumenty, výsledky a vlastnosti. Sjednocení přijme každý uvedený typ. strict_types volajícího souboru brání běžným skalárním převodům, int však stále vyhoví float. Pole místo int nebo string vyvolá TypeError.

declare(strict_types=1); function code(int|string $v):string{return get_debug_type($v);}
echo code("7")," ",code(7);try{code([]);}catch(TypeError $e){echo " ",get_class($e);}
function countOnly(int $v):int{return $v;} function decimal(float $v):string{return get_debug_type($v);} try{countOnly("7");}catch(TypeError $e){echo "\n",get_class($e)," ",decimal(7);}
string int TypeError
TypeError float

Příklady

<?php
declare(strict_types=1); function code(int|string $v):string{return get_debug_type($v);}
echo code("7")," ",code(7);try{code([]);}catch(TypeError $e){echo " ",get_class($e);}
function countOnly(int $v):int{return $v;} function decimal(float $v):string{return get_debug_type($v);} try{countOnly("7");}catch(TypeError $e){echo "\n",get_class($e)," ",decimal(7);}

Výsledek

string int TypeError
TypeError float

Zdroje