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

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
主站蜘蛛池模板: 大新县| 织金县| 龙陵县| 洛川县| 布拖县| 宁国市| 平阳县| 杂多县| 蓬溪县| 康平县| 六盘水市| 厦门市| 合山市| 明水县| 象州县| 威信县| 通州区| 乌鲁木齐县| 太白县| 芜湖县| 绵阳市| 永善县| 合肥市| 那坡县| 中宁县| 闻喜县| 大石桥市| 宁化县| 河北区| 清原| 灵台县| 类乌齐县| 德令哈市| 东乡| 乌海市| 宣武区| 富民县| 昌平区| 贡觉县| 郧西县| 莱芜市|