Return type declaration
Just like parameter type, there is also a return type; it is also optional it is a safe practice to specify the return type.
This is how we can declare a return type:
<?php
function add($num1, $num2):int{
return ($num1+$num2);
}
echo add(2,4); //6
echo add(2.5,4); //6
As you can see in the case of 2.5
and 4
, it should be 6.5
, but as we have specified int
as a return type, it is performing implicit type conversion. To avoid this and to obtain an error instead of an implicit conversion, we can simply enable a strict type, as follows:
<?php declare(strict_types=1); function add($num1, $num2):int{ return ($num1+$num2); } echo add(2,4); //6 echo add(2.5,4); //Fatal error: Uncaught TypeError: Return value of add() must be of the type integer, float returned