Read Time:36 Second
PHP Function Return Type Declarations

PHP 7 also supports Type Declarations for the return
statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a “Fatal Error” on a type mismatch.
To declare a type for the function return, add a colon ( :
) and the type right before the opening curly ( {
)bracket when declaring the function.
Example#1
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
Example#2
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
Average Rating