使用类型提示时无法传递空参数 [英] Cannot pass null argument when using type hinting
问题描述
以下代码:
<?php
class Type {
}
function foo(Type $t) {
}
foo(null);
?>
在运行时失败:
PHP Fatal error: Argument 1 passed to foo() must not be null
为什么不允许像其他语言一样传递null?
Why is it not allowed to pass null just like other languages?
推荐答案
PHP 7.1或更高版本(于2016年12月2日发布)
PHP 7.1 or newer (released 2nd December 2016)
您可以使用此语法将变量明确声明为null
You can explicitly declare a variable to be null
with this syntax
function foo(?Type $t) {
}
这将导致
$this->foo(new Type()); // ok
$this->foo(null); // ok
$this->foo(); // error
因此,如果要使用可选参数,则可以遵循惯例Type $t = null
,而如果需要使参数同时接受null
及其类型,则可以遵循上面的示例.
So, if you want an optional argument you can follow the convention Type $t = null
whereas if you need to make an argument accept both null
and its type, you can follow above example.
您可以在此处了解更多信息.
You can read more here.
PHP 7.0或更早版本
您必须添加一个默认值,例如
You have to add a default value like
function foo(Type $t = null) {
}
这样,您可以向其传递一个空值.
That way, you can pass it a null value.
这在手册中有关类型声明:
如果参数的默认值设置为
NULL
,则可以使声明接受NULL
值.
The declaration can be made to accept
NULL
values if the default value of the parameter is set toNULL
.
这篇关于使用类型提示时无法传递空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!