What is type juggling and strict_types in PHP?
Type juggling means PHP converts the data type of a value automatically when needed. For example, the string "10" is treated as a number when you compare or add it with a number.
<?php
var_dump("10" == 10); // string and number, values are same
var_dump("abc" == 0); // false in PHP 8 (it was true in PHP 7)
var_dump(0 == ""); // false in PHP 8 (it was true in PHP 7)
?>
Output:
Output in PHP 8
bool(true)
bool(false)
bool(false)
This automatic change can create bugs. You can ask PHP to be strict with declare(strict_types=1). It must be the first statement of the file, and it affects the function calls made from that file.
<?php
declare(strict_types=1);
function add(int $a, int $b) {
return $a + $b;
}
echo add(2, 3); // 5
// echo add("2", "3"); // TypeError, because strings are not accepted
?>
Output:
Tutorials Class - Output Window
5
To be safe, compare with === and use type declarations in functions. See == vs ===.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Variables |
| PHP Data Types |
| PHP Constants |
| PHP isset() Function |
| PHP empty() Function |
| PHP is_null() Function |
| Exercises & Assignments |
|---|
| Write a program to print “Hello PHP” using variable |
| Write a program to print a string using echo+variable. |
| Write a program to print two variables in single echo |