osc*_*ago 25 php arguments function
我正在尝试使用声明的参数类型创建一个函数,以快速检查它们是否采用正确的格式,但是当它返回一个字符串时我发生了以下错误:
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);
Run Code Online (Sandbox Code Playgroud)
哪里出错了?
小智 13
这对于自PHP 7可用性以来看过这篇文章的人来说可能很有用
使用PHP 7,现在可以声明类型.您可以参考以下链接以获取更多信息.
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
function(string $name, boolean $is_admin) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
你可以做这样一直对我有用的事情
对于字符串
function setData($Name=""){ }
Run Code Online (Sandbox Code Playgroud)
这会强制名称为字符串,但不会检查其是否为字符串
对于数值
function setData($age=0){ }
Run Code Online (Sandbox Code Playgroud)
这会强制年龄为数字,如果传递一个字符串,则该值将为0
对于数组值,有两种变化
function setData(array $data){ }
Run Code Online (Sandbox Code Playgroud)
如果没有传递数组,则会抛出错误
function setData($data=array()){ }
Run Code Online (Sandbox Code Playgroud)
这将传递一个没有值的空数组 $data
根据PHP Manual,您可以array
在PHP 5.1及更高版本以及PHP 7及更高版本上为string
和int
类型执行此操作。看一看:
Class/interface name
参数必须是给定类或接口名称的实例。 PHP 5.0.0self
参数必须是与定义方法的类相同的类的实例。这只能用于类和实例方法。 PHP 5.0.0
array
参数必须是一个数组。PHP 5.1.0
callable
该参数必须是有效的可调用对象。PHP 5.4.0bool
参数必须是布尔值。 PHP 7.0.0float
参数必须是浮点数。 PHP 7.0.0
int
参数必须是整数。 PHP 7.0.0
string
参数必须是字符串。PHP 7.0.0
iterable
参数必须是数组或 Traversable 的实例。PHP 7.1.0