What does declare(strict_types=1);
do in PHP?
PHP is a weakly typed language, which means that when a value is of the wrong type, PHP tries to cast it to the proper type.
For example if you try to add an integer and a string,
echo 5 + "3";
PHP will try to cast the string ("3"
) to an integer (3
) and use that value, so our result is 8
.
Weakly Typed Type Hints
When we type hint a function argument, PHP will do this same casting.
Type Hint Casting
Here our function is expecting an integer but instead we pass it a string ("3"
).
This is okay because, PHP casts our string ("3"
) to an integer (3
) and uses that value.
function outputAnInteger(int $num)
{
echo $num;
}
outputAnInteger("3");
Our output is 3
.
Strict Type Hints
By adding the line
declare(strict_types=1);
to the beginning of the file, function calls will respect type hints strictly (they will not be cast to another type).
declare(strict_types=1);
function outputAnInteger(int $num)
{
echo $num;
}
outputAnInteger("3");
This code results in
Fatal error: Uncaught TypeError: Argument 1 passed to outputAnInteger() must be of the type int, string given
Where to declare strict_types
The declare(strict_types=1);
is applied to all function calls being made in the file where it is declared.
In other words, if I declare my function in a file called functions.php
function outputAnInteger(int $num)
{
echo $num;
}
and I make the loosely typed call outputAnInteger("3");
from a file called mylogic.php
- mylogic.php adding
declare(strict_types=1);
would cause a Fatal PHP error - functions.php adding
declare(strict_types=1);
would have no effect on theoutputAnInteger("3");
call (which appears inmylogic.php
)
Leave a Reply