Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Type system and declarations

Type declarations check arguments, return values and properties.

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

Syntax

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

Type declarations check arguments, return values and properties. A union accepts any listed type. In strict scalar calls, the caller’s strict_types setting prevents ordinary scalar coercion, with int still accepted for float. Passing an array where int|string is required raises 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

Examples

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

Result

string int TypeError
TypeError float

Sources