官术网_书友最值得收藏!

Return type declaration

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:

<?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
主站蜘蛛池模板: 陆丰市| 澄迈县| 广州市| 怀安县| 高碑店市| 东乌| 白玉县| 镇宁| 绵阳市| 沙河市| 水城县| 子洲县| 林州市| 永丰县| 龙里县| 敦化市| 昆明市| 石台县| 若尔盖县| 名山县| 鱼台县| 游戏| 宜昌市| 东乌珠穆沁旗| 循化| 潮安县| 东辽县| 建水县| 三穗县| 竹北市| 广平县| 延寿县| 武夷山市| 五常市| 白水县| 宁津县| 辉县市| 蓝田县| 临邑县| 盐边县| 澜沧|