Strict Types
Strict types is a mode that makes typed calls check argument types exactly. A file turns the mode on with a declare line at the top.
The default mode converts a string argument
The function asks for int values. The call passes the text 5, and the default mode converts it to the number 5.
<?php
function add(int $a, int $b): int {
return $a + $b;
}
echo add("5", 3), "\n";An int widens to a float in strict mode
The declare line turns strict mode on for this file. An int still widens to a float parameter, and plain int calls still work.
<?php
declare(strict_types=1);
function show(float $x): void {
var_dump($x);
}
function add(int $a, int $b): int {
return $a + $b;
}
show(5);
echo add(2, 3), "\n";A string argument is refused in strict mode
The same call from the first snippet now runs under the declare line. Strict mode refuses the string and stops the program.
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
echo add("5", 3), "\n";A float argument is refused for an int parameter
The call passes a float where the function asks for an int. Strict mode refuses the value instead of cutting off the decimal part.
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
echo add(5.9, 3), "\n";Example
<?php
declare(strict_types=1);
function total(int $price, int $count): int {
return $price * $count;
}
function rate(float $value): float {
return $value;
}
var_dump(rate(2));
echo total(250, 3), "\n";Key points
- The default mode converts some argument values to the declared type.
- The declare line turns strict checking on for one file.
- Strict checking applies to calls made from the file that holds the declare line.
- An int value still widens to a float parameter in strict mode.
- A float value passed to an int parameter is refused in strict mode.
- A string value passed to an int parameter raises a TypeError in strict mode.
In this example, the declare line turns strict mode on for the whole file. The rate call passes an int to a float parameter, and the dump shows the widened float value. The total call passes two clean int values and prints 750.
Note
The rest of this course stays in the default mode unless a file shows the declare line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the declare line for strict types do in a file?