This article will introduce to you how to enable strong type mode in php7. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
We know that php is a weakly typed programming language, but php7 has changed and can support code to enable strong type mode. Good news.
php7 enables strong type mode, which is part of the reason why php7 has improved efficiency compared to previous versions. Let’s look at two examples first
First
<?php function sum($a,$b):float { return $a+$b; } var_dump(sum(1,2)); var_dump(sum(1,2.5)); ?>
The output result is:
float(3) float(3.5)
Then add the strong type mode
<?php define(strict_types=1);//注意这一句必须要放在第一行,而且顶格 function sum($a,$b):float { return $a+$b; } var_dump(sum(1,2)); var_dump(sum(1,2.5)); ?>
The output result is:
float(3) float(3.5)
It seems that there is no difference from here, because int->float type conversion is allowed .
Let’s look at another example:
function sum(int $a,int $b):float { return $a+$b; } var_dump(sum(1,2)); var_dump(sum(1,2.5));
The output result is:
float(3) float(3)
This is because 2.5 is forced to be converted to int type, the value is 2, 1 2=3, There is nothing wrong with the result, but generally speaking, this implicit conversion is too difficult to understand and may not be the result we expected.
So we add the strong type mode to see the output result. The code is as follows:
<?php declare(strict_types=1); function sum(int $a,int $b):float { return $a+$b; } var_dump(sum(1,2)); var_dump(sum(1,2.5)); ?>
The output result is:
float(3) Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, float given, called in /home/www/learn.php on line 8 and defined in /home/www/learn.php:3 Stack trace: #0 /home/www/learn.php(8): sum(1, 2.5) #1 {main} thrown in /home/www/learn.php on line 3
It can be seen here that the strong type mode is in effect. There is an error in the sum(1,2.5) sentence. 2.5 is not an int type, causing an error in the program.
If we encounter this situation, let us catch this error by catching an exception
The code is as follows:
<?php declare(strict_types=1); function sum(int $a,int $b):float { return $a+$b; } try { var_dump(sum(1,2)); var_dump(sum(1,2.5)); } catch(TypeError $e) { echo 'Error:'.$e->getMessage(); } ?>
The output result is:
float(3) Error:Argument 2 passed to sum() must be of the type integer, float given, called in /home/www/learn.php on line 9
Recommended learning: php video tutorial
The above is the detailed content of How to enable strong type mode in php7. For more information, please follow other related articles on the PHP Chinese website!