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

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
主站蜘蛛池模板: 收藏| 巴彦县| 册亨县| 玉屏| 南涧| 揭西县| 丁青县| 苏尼特左旗| 唐山市| 安平县| 德兴市| 务川| 孝感市| 墨竹工卡县| 浠水县| 吐鲁番市| 怀远县| 和平县| 手机| 莆田市| 漳州市| 封开县| 班戈县| 彩票| 永年县| 元江| 综艺| 松原市| 新竹县| 临汾市| 新昌县| 宁夏| 揭西县| 武平县| 涿鹿县| 广西| 陆良县| 浏阳市| 海阳市| 迁安市| 闵行区|