PHP Return Types & Type Declarations
PHP allows you to declare the expected types of function parameters and return values, which is called type hinting or type declarations. This helps catch bugs early and makes your code's intent clearer.
You can specify types like int, float, string, bool, array, or a class name for parameters, and add a return type after the parameter list using a colon. PHP will throw a TypeError if the wrong type is passed in strict mode.
function add(int $a, int $b): int {
return $a + $b;
}Parameter type declarations
Adding a type before a parameter name, like function setAge(int $age), tells PHP (and other developers) exactly what type is expected.
Return type declarations
A colon followed by a type after the parameter list, like function add(int $a, int $b): int, declares what type the function will return.
<?php
function add(int $a, int $b): int {
return $a + $b;
}
echo add(2, 3);
?>5Both parameters and the return value are declared as int, making the contract clear.
<?php
function greet(string $name): string {
return "Hi, $name";
}
echo greet("Amy");
?>Hi, AmyThe function only accepts a string and promises to return a string.
Key points
- Type declarations specify expected types for parameters and return values.
- A colon before the function body declares the return type.
- declare(strict_types=1); enforces strict type checking.
- Type declarations make code easier to understand and debug.
