CKTIS / PHP
Sistema de tipos y declaraciones
Las declaraciones comprueban argumentos, retornos y propiedades.
Versión: PHP 8.4; repository runtime, production runtime not attested
Sintaxis
declare(strict_types=1); function code(int|string $v): string { /* ... */ }Las declaraciones comprueban argumentos, retornos y propiedades. Una unión acepta cualquiera de sus tipos. strict_types del archivo llamante evita conversiones escalares normales, aunque int sigue admitido para float. Un array donde se exige int o string produce 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
Ejemplos
<?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);}
Resultado
string int TypeError TypeError float