Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / PHP

Système de types et déclarations

Les déclarations de type vérifient arguments, retours et propriétés.

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

Syntaxe

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

Les déclarations de type vérifient arguments, retours et propriétés. Une union accepte chaque type listé. strict_types du fichier appelant empêche les conversions scalaires usuelles, mais int convient à float. Un tableau au lieu de int ou string lève 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

Exemples

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

Résultat

string int TypeError
TypeError float

Sources