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

Scalar type declaration

In PHP7, we can now declare the type of parameters being passed to a function. They could be only user defined classes in previous versions, but now they can be scalar types as well. By scalar type, we mean basic primitive types, such as int, string, and float.

Previously, to validate an argument passed to a function, we needed to use some sort of if-else. So, we used to do something like this:

<?php
function add($num1, $num2){
if (!is_int($num1)){
throw new Exception("$num1 is not an integer");
}
if (!is_int($num2)){
throw new Exception("$num2 is not an integer");
}

return ($num1+$num2);
}

echo add(2,4); // 6
echo add(1.5,4); //Fatal error: Uncaught Exception: 1.5 is not an integer

Here we used if to make sure that the type of the variables $num1 and $num2 is int, otherwise we are throwing an exception. If you are a PHP developer from the earlier days who likes to write as little code as possible, then chances are that you were not even checking the type of parameter. However, if you do not check the parameter type then this can result in a runtime error. So to avoid this, one should check the parameter type and that is what PHP7 has made easier.

This is how we validate parameter type now in PHP7:

<?php
function add(int $num1,int $num2){
return ($num1+$num2);
}
echo add(2,4); //6
echo add("2",4); //6
echo add("something",4);
//Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given

As you can see now, we simply type hint as int and we do not need to validate each parameter separately. If an argument will not be an integer, it should throw an exception. However, you can see that it didn't show TypeError when 2 was passed as a string and instead it did an implicit conversion and assumed it as int 2. It did so because, by default, the PHP code was running in coercive mode. If strict mode is enabled, writing "2" instead of 2 will cause TypeError instead of the implicit conversion. To enable a strict mode, we need to use the declare function at the start of the PHP code.

This is how we can do this:

<?php
declare(strict_types=1);

function add(int $num1,int $num2){
return ($num1+$num2);
}

echo add(2,4); //6
echo add("2",4); //Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given,

echo add("something",4); // Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given
主站蜘蛛池模板: 瓦房店市| 舟曲县| 泰宁县| 平度市| 丹江口市| 庆城县| 喀喇| 济源市| 北安市| 谢通门县| 香港| 梨树县| 准格尔旗| 永新县| 曲阳县| 师宗县| 青冈县| 望城县| 资兴市| 祁连县| 乌拉特前旗| 仁怀市| 镇赉县| 昌乐县| 康乐县| 河北省| 徐汇区| 汤阴县| 聂荣县| 贺兰县| 营口市| 望奎县| 宜兴市| 台南市| 手游| 原平市| 杭锦后旗| 正宁县| 襄樊市| 东阿县| 晋江市|