This post covers the Type Hinting section of the OOP chapter when studying for the Zend PHP 7 Certification.
Type declarations, or type hints as they were previously known, are used to specify the expected data type of an argument in a function declaration.
Prior to PHP 7, you could use the following types.
Now, you can use scalar types.
Here is a basic function expecting two arguments that are of the int
data type.
function sum(int $a, int $b) {
return $a + $b;
}
var_dump(sum(1, 2));
// Outputs: int(3)
If the given value is of the incorrect type, then an error is generated. In PHP 5, this will be a recoverable fatal error, while PHP 7 will throw an uncaught TypeError
exception.
You can catch a TypeError
within a try-catch block.
try {
var_dump(sum('string1', new stdClass()));
} catch (TypeError $e) {
echo 'Error: '.$e->getMessage();
}
The default behaviour of PHP is that it will try and coerce values of the wrong type into the expected scalar type if possible. If for example, a function that is given an integer for a parameter that expects a string will get a variable of type string.
If strict mode is enabled (which can be done on a per-file basis), only a variable of exact type of the type declaration will be accepted, or a TypeError
will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float.
Strict mode can be enabled by using the declare()
construct.
declare(strict_types=1);
function sum(int $a, int $b) {
return $a + $b;
}
var_dump(sum('1', '2')); // TypeError thrown
View the other sections:
Note: This article is based on PHP version 7.0.