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

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
主站蜘蛛池模板: 新化县| 城口县| 贵德县| 常熟市| 班戈县| 吉首市| 石林| 锦屏县| 德江县| 桂阳县| 宜黄县| 连云港市| 明溪县| 廊坊市| 噶尔县| 长顺县| 太仓市| 公安县| 岑溪市| 灵石县| 泰安市| 伊宁县| 乌拉特前旗| 汾阳市| 盐山县| 中西区| 军事| 白银市| 湖南省| 乌苏市| 莱西市| 西城区| 叶城县| 台安县| 通州区| 肃宁县| 崇义县| 新津县| 宁陕县| 耒阳市| 昭平县|