How to work with type declarations
Two functions that use type declarations
A function with one parameter type declaration
function display_error(string $error) {
echo("<p class='error'>$error</p>\n");
}
A function with type declarations for its parameters and return value
function avg_of_3(int $x, int $y, int $z) : float {
$avg = ($x + $y + $z) / 3;
return $avg;
}
Function calls without strict typing
display_error('Value out of range.'); // Displays 'Value out of range.'
display_error(1); // Displays '1'
$average = avg_of_3(5, 2, 8); // $average is 5
$average = avg_of_3(5.1, 2.7, 8.2); // $average is 5
How to enable strict types mode
declare(strict_types=1); // must be first line of script
Function calls with strict typing
display_error('Value out of range.'); // Displays 'Value out of range.'
display_error(1); // Fatal error
$average = avg_of_3(5, 2, 8); // $average is 5
$average = avg_of_3(5.1, 2.7, 8.2); // Fatal error
A typical error message when the data type isn’t correct
TypeError: Argument 1 passed to avg_of_3() must be of the type integer, float given
- With PHP 5, you can declare the type of a parameter for a function and the return type of a function as object types. This includes built-in object types such as the array type as well as user-defined object types such as the Product type described in the next chapter.
- With PHP 7 and later, you can also declare parameter and return types as scalar types such as the int, float, string, and bool types.
- By default, PHP converts a value to the specified type whenever possible.
- If you enable strict types mode and a function receives an argument of an incorrect type, PHP throws an exception.
Back