Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / PHP

Sustav tipova i deklaracije

Deklaracije tipa provjeravaju argumente, rezultate i svojstva.

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

Sintaksa

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

Deklaracije tipa provjeravaju argumente, rezultate i svojstva. Unija prihvaća svaki navedeni tip. strict_types pozivajuće datoteke sprječava obične skalarne pretvorbe, ali int i dalje odgovara float. Polje umjesto int ili string izaziva 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

Primjeri

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

Rezultat

string int TypeError
TypeError float

Izvori