Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

Sistema de tipos e declarações

As declarações verificam argumentos, retornos e propriedades.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

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

As declarações verificam argumentos, retornos e propriedades. Uma união aceita cada tipo indicado. strict_types do ficheiro chamador impede conversões escalares normais, embora int continue aceite para float. Um array em vez de int ou string gera 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

Exemplos

<?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

Fontes