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

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
主站蜘蛛池模板: 信丰县| 高陵县| 巧家县| 乌恰县| 夹江县| 遂川县| 高要市| 进贤县| 威远县| 白朗县| 志丹县| 盐池县| 广州市| 栖霞市| 河间市| 普格县| 遵义市| 大同县| 封丘县| 调兵山市| 鲁甸县| 靖宇县| 上虞市| 友谊县| 阿拉善盟| 老河口市| 虹口区| 浦城县| 雷波县| 嘉善县| 樟树市| 贵南县| 黑河市| 阿巴嘎旗| 庄河市| 华蓥市| 北辰区| 青铜峡市| 疏勒县| 凤山市| 南宫市|