What are type declarations in PHP, and how do they let you specify what kind of value a function parameter or return value should be?
Short answer
Type declarations let you explicitly specify the expected data type of a function's parameters and its return value directly within the function's signature, such as declaring that a parameter must be a string or an integer, and if a value of the wrong type is passed in, PHP…
Advertisement
AModel answer
Type declarations let you explicitly specify the expected data type of a function's parameters and its return value directly within the function's signature, such as declaring that a parameter must be a string or an integer, and if a value of the wrong type is passed in, PHP will either automatically attempt to convert it to the expected type or raise an error, depending on your configuration, which helps catch mistakes early and makes a function's expected usage much clearer to anyone reading the code.
function calculateTotal(float $price, int $quantity): float {
return $price * $quantity;
}Real-world example
A shopping cart calculation function declares that it expects a float price and an integer quantity, immediately making it clear to any other developer exactly what kind of values should be passed in, and catching an accidental mistake if a string were passed instead.
Likely follow-ups
- What data types can be used in a PHP type declaration?
- What happens if you do not provide any type declaration at all for a parameter?
Related topics