function foobar(MyClass $foo) {
// do stuff
}
foobar(new NotMyClass()); // throws an error
This just adds type hints for the scalar types (integer, float, string and boolean).Since PHP has a long tradition of weak typing and this is what PHP's built-in and extension functions use, weak is the default behaviour, allowing some conversions:
function foo(int $x) {
var_dump($x);
}
foo("12"); // produces int(12)
foo(null); // throws an error
But, you can optionally turn on a strict type-checking mode for scalars on a per-file basis, which doesn't allow conversions: <?php
declare(strict_types=1);
function foo(int $x) {
var_dump($x);
}
foo("12"); // throws an error
foo(null); // throws an errorfunction foo(int $x) { // x is guaranteed to be an int. }
The type-hinting for scalars has two modes:
* strict - the parameter passed to the function must be of the exact* type. * weak - the parameter passed to the function will be converted to the correct type.
The strictness depends on what mode PHP was in when the function was called. This is the right choice as it:
* Allows library authors to write their code in either strict or weak mode.
* End-users to write their code in either strict or weak mode. Or even without using scalar type-hints.
* End-user to be able to choose when they are writing their code do they want their variables to be converted to the type expected by the library automatically, or do they want PHP to give them an error if they accidentally pass the wrong type of variable to a function that is expecting an int.
*except for some widening rules, e.g. you can pass an int where a float is expected, as ints can be converted into float without data loss (for ints less than 2^53).