php:声明函数的参数类型

2022-08-30 12:00:03

我正在尝试使用声明的参数类型创建一个函数,以快速检查它们的格式是否正确,但是当它返回字符串I时,会出现此错误:

Catchable fatal error: Argument 2 passed to myfunction() must be an instance of string, string given, called in path_to_file on line 69 and defined in path_to_file on line 49

function myfunction( array $ARRAY, string $STRING, int $INTEGER ) { 
    return "Args format correct"; 
}
myfunction(array("1",'2','3','4'), "test" , 1234);

错误在哪里?


答案 1

根据 PHP5 文档

类型提示只能是对象和数组(从 PHP 5.1 开始)类型。不支持使用 int 和字符串的传统类型提示。

由于 和 不是类,因此不能在函数中“类型提示”它们。stringint

从 PHP 7.0 开始,支持将参数类型声明为字符串、int、float、bool。


答案 2

对于自 PHP 7 发布以来看到此帖子的任何人来说,这可能很有用

在 PHP 7 中,现在可以声明类型。有关详细信息,请参阅以下链接。

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

function(string $name, bool $is_admin) {
    //do something
}

推荐