Strong typing was introduced in PHP 7, thanks to which it became possible to specify the types of arguments to functions (methods) and the return type.
By default, PHP 7, when operating in loosely typed mode, will try to convert values of another type to the expected scalar type if possible.
function getAge (string $age ) { var_dump ($age); } $age = 33; getAge($age); // string (2) "33"
Without strong typing, PHP converted the integer 33 to the string “33” as expected.
PHP 7 introduced the declare(strict_types=1); directive, which enables strict mode. In strict mode, only a variable of the exact, given type will be accepted, or a TypeError will be thrown. The only exception to this rule is that a function that expects a float can return an integer.
Now our past example will output an error and will not work:
declare(strict_types = 1); function getAge(string $age) { var_dump($age); } $age = 33; getAge($age);
By running the code, we take:
! The only exception to the strong typing rule is that a function that expects a float can return an integer:
declare(strict_types = 1); function getFloat(float $f) : int { return (int) $f; } $int = getFloat(100);