September 2017
Intermediate to advanced
244 pages
6h 44m
English
Just like parameter type, there is also a return type; it is also optional but it is a safe practice to specify the return type.
This is how we can declare a return type:
<?phpfunction add($num1, $num2):int{ return ($num1+$num2);}echo add(2,4); //6echo 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:
<?phpdeclare(strict_types=1);function add($num1, $num2):int{ return ($num1+$num2);}echo add(2,4); //6echo add(2.5,4); //Fatal error: Uncaught TypeError: Return value of add() must be of ...Read now
Unlock full access