By default, PHP is forgiving with function arguments. If a function asks for an int and you pass the string "5", PHP converts it for you.
<?php
function double(int $n): int
{
return $n * 2;
}
echo double("5");
10
That works, but it can hide mistakes. With strict typing turned on, PHP refuses to convert.
Turn on strict types
Put this line at the very top of the file, right after <?php:
<?php
declare(strict_types=1);
function double(int $n): int
{
return $n * 2;
}
try {
echo double("5");
} catch (TypeError $e) {
echo "Error: " . $e->getMessage();
}
Error: double(): Argument #1 ($n) must be of type int, string given, called in /path/to/index.php on line 10
Now a string cannot sneak in as an int. You get a clear TypeError right where the bad value entered.
What strict types changes
- Calls to your functions are checked exactly.
- Calls to built-in functions from this file are checked exactly too.
- Return values are checked exactly.
One small exception: an int is still allowed where a float is expected, because it loses no information.
What strict types does not change
- It does not change
+,==or other operators."5" + 5still works. - It applies per file. A file without the line stays in the forgiving mode, even if it calls code from a strict file.
Why use it
Mistakes appear when you write them instead of three pages later. Most modern PHP projects and frameworks start every file with this line.
<?php
declare(strict_types=1);
namespace App;
It must be the first statement
declare(strict_types=1); has to come before any other code in the file. If there is output or other code before it, PHP throws a fatal error.Exercise: spot the error
With strict types on, which of these calls would throw a TypeError for function show(string $text): show("hi"), show(5), show("5")?
Show the answer
Only show(5) throws, because 5 is an integer and the function wants a string. "hi" and "5" are both strings.