Declaring parameter types in PHP functions improves code readability and enforces type checking, reducing the risk of passing incompatible values. This feature is available starting from PHP 7.0 and supports both parameter and return type declarations.
function funcName(type $param1, type $param2): type {
// Function body
}
Type declarations allow developers to explicitly define what types of values a function expects and what it returns. Here's an example of a function that takes a string and returns a string:
function toUpperCase(string $name): string {
return strtoupper($name);
}
This function requires $name to be a string. If a value of another type is passed, a type error will be triggered.
PHP also supports default values for parameters with type declarations. This allows the function to operate even when certain arguments are omitted:
function greet(string $name, int $age = 0): void {
// Function body
}
In this example, $age is an optional parameter with a default value of 0 and must be of type int.
Using parameter type declarations in PHP functions is a best practice that enhances code quality, prevents common bugs, and promotes a more maintainable codebase. Whether you're writing new functions or refactoring legacy code, type hints are a valuable tool for any PHP developer.