Junior
What is strict mode in PHP?
sobes.tech AI
Answer from AI
Strict mode in PHP, enabled by the directive declare(strict_types=1);, affects how the PHP engine handles type coercion when calling functions and methods.
Without strict mode (default), PHP performs implicit type coercion. For example, if a function expects an argument of type int, and a string "123" is passed, PHP will attempt to convert the string to an integer.
With strict mode, PHP does not perform implicit type coercion for scalar types (int, float, string, bool). If the type of the passed value does not match the declared parameter type, a TypeError will be thrown.
Important:
declare(strict_types=1);only applies to the file in which it is declared. When enabled in one file, it does not affect other files that include it (require/include), unless those files also declare strict mode.- Strict mode does not affect return values or typed class properties. It strictly applies to function and method arguments.
Example:
Without strict mode (default behavior):
<?php
function sum(int $a, int $b): int {
return $a + $b;
}
echo sum("1", "2"); // Outputs 3 (implicit type coercion)
?>
With strict mode:
<?php
declare(strict_types=1);
function sum(int $a, int $b): int {
return $a + $b;
}
// echo sum("1", "2"); // Throws TypeError
echo sum(1, 2); // Outputs 3
?>
Advantages of using strict mode:
- Increases code predictability.
- Reduces errors related to implicit type coercion.
- Improves code readability and documentation, as types are explicitly specified and enforced.
Disadvantage:
- May require refactoring existing code that heavily relies on implicit type coercion.