函数参数特定类型声明
原链接 https://www.php.net/manual/zh/functions.arguments.php
类型声明允许函数在调用时要求参数为特定类型。 如果给出的值类型不对,那么将会产生一个错误: 在PHP 5中,这将是一个可恢复的致命错误,而在PHP 7中将会抛出一个TypeError异常。
为了指定一个类型声明,类型应该加到参数名前。这个声明可以通过将参数的默认值设为NULL
来实现允许传递NULL
。
Valid types
Type | Description | Minimum PHP version |
---|---|---|
Class/interface name | The parameter must be an instanceof the given class or interface name. | PHP 5.0.0 |
self | The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. | PHP 5.0.0 |
array | The parameter must be an array. | PHP 5.1.0 |
callable | The parameter must be a valid callable. | PHP 5.4.0 |
bool | The parameter must be a boolean value. | PHP 7.0.0 |
float | The parameter must be a floating point number. | PHP 7.0.0 |
int | The parameter must be an integer. | PHP 7.0.0 |
string | The parameter must be a string. | PHP 7.0.0 |
iterable | The parameter must be either an array or an instanceof Traversable. | PHP 7.1.0 |
object | The parameter must be an object. | PHP 7.2.0 |