Type hinting in PHP refers to the practice of specifying the expected data types for function arguments, return values, and class properties.
It helps ensure that the values passed to or returned from a function adhere to the expected type, which improves code clarity, reliability, and reduces runtime errors.
function add(int $a, int $b): int {
return $a + $b;
}
echo add(2, 3); // Output: 5class User {
public string $name;
}
function greet(User $user): string {
return "Hello, " . $user->name;
}
$user = new User();
$user->name = "John";
echo greet($user); // Output: Hello, JohnPHP introduced type hinting in stages:
- PHP 5: Introduced type hints for class names, arrays, and
callable. - PHP 7: Added scalar type hints (
int,float,string,bool) and return type declarations. - PHP 7.4: Introduced typed properties for classes.
- PHP 8: Enhanced type hinting with union types, static types, and mixed types.
