PHP Type Hinting and Return Types
PHP is a loosely typed language, meaning you don't strictly have to declare the data types of variables. However, modern PHP allows you to specify expected data types for function arguments and return values. This is known as Type Hinting.
1. Argument Type Declarations
You can specify the expected data type for function arguments. If the wrong type is passed, PHP will throw a TypeError.
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, 5);
Supported types include: int, float, string, bool, array, iterable, object, class/interface names, and self.
2. Return Type Declarations
You can also specify the data type a function must return using a colon : before the opening curly brace.
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
3. Strict Typing
By default, PHP will try to convert wrong types (e.g., string "5" to int 5). To enforce strict type checking, place this declaration at the very top of your PHP file:
declare(strict_types=1);
function add(int $a, int $b) { return $a + $b; }
// add(5, "5"); // Fatal Error: Argument 2 must be of type int
4. Nullable Types
If a parameter or return value can be a specific type or null, prefix the type with a question mark ?.
function getAddress(?string $address) {
if ($address) {
echo "Address: " . $address;
} else {
echo "No address provided.";
}
}
5. Union Types (PHP 8.0+)
Union types allow a value to be one of multiple types, separated by a vertical bar |.
function processInput(int|float $number) {
return $number * 2;
}