PHP 7 uses two types of hinting in scalar type declaration and return type declaration −
- Weak type hinting
- Strict type hinting
Weak type hinting
By default, PHP 7 works in weak type checking mode.Weak type checking will not give any error or fatal error.When a type declaration mismatch occurs it will simply execute the code without throwing any error.
By using strict_typesdeclare(), we can control the weak type checking.
declare(strict_types=0); //weak type-checking; we should set the strict value = 0
Weak type hinting Example 1
<?php $x=10; // integer variable x =10 value $y=20.20; // using floating point number y=20.20 value function add(int $x, int $y){ return $x + $y; } echo add($x, $y); ?>
Output
The code will produce the following output −
30
Explanation
In the above example, we are not using a strict value for a parameter. We used two integer variables, x, and y. For x=10 and y is using the floating number 20.20, but y will not produce any error; it will simply give the output integer value 30.
Example 2
<?php function returnadd(int ...$integers){ return array_sum($integers); } var_dump(returnadd(2, '3', 4.1)); ?>
Output
The output for the above program will be −
int(9)
Strict type hinting
Strict type hinting will give a Fatal Error when a type declaration mismatch occurs. We can say that strict type hinting accepts a variable of the exact type of the type declaration, else it will throw the TypeError mismatch.
In the strict type hinting, the first statement in a file must be declared (strict_types=1), otherwise, it will produce a compiler error. It does not affect the other included files which are not specified in files, which means it only affects the specific file it is used.
The strict type hinting directive is completely compile-time and cannot be controlled at runtime.
Strict type hinting Example 1
<?php declare (strict_types=1); function returnadd(float $x , float $y){ return $x+$y; } var_dump(returnadd(3.1,2.1)); //output float(5.2) var_dump(returnadd(3, "2 days")); //fatal error ?>
Output
The above strict type hinting program will be −
float(5.2) Fatal error: Uncaught TypeError: Argument 2 passed to returnadd() must be of the type float, string given, called in C:\xampp\htdocs\gud.php on line 7 and defined in C:\xampp\htdocs\gud.php:3 Stack trace: #0 C:\xampp\htdocs\gud.php(7): returnadd(3, '2 days') #1 {main} thrown in C:\xampp\htdocs\gud.php on line 3
Strict type hinting Example 2
<?php declare(strict_types=1); // strict mode checking $x='1'; // string $y=20; //integer number function add(int $x, int $y){ return $x + $y; } var_dump(add($x, $y)); ?>
It will produce the output “fatal error”
In the above strict type declaration example, if we declare the strict_type value is 1, the code will give the output “Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, a string is given”.