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

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
主站蜘蛛池模板: 鄂州市| 满洲里市| 泗洪县| 南岸区| 北辰区| 运城市| 潜江市| 新乡县| 浦江县| 通榆县| 胶南市| 兰西县| 温宿县| 沐川县| 泸溪县| 杭锦旗| 崇义县| 芷江| 汝南县| 大同县| 泸州市| 秦皇岛市| 梅州市| 扎兰屯市| 将乐县| 永年县| SHOW| 顺昌县| 阳新县| 勐海县| 张家口市| 景宁| 巴林左旗| 东阿县| 江油市| 越西县| 金川县| 来宾市| 万山特区| 德格县| 夏河县|