218

以下代码:

class Type {

}

function foo(Type $t) {

}

foo(null);

运行时失败:

PHP 致命错误:传递给 foo() 的参数 1 不能为空

为什么不允许像其他语言一样传递 null ?

4

5 回答 5

411

PHP 7.1 或更新版本(2016 年 12 月 2 日发布)

您可以null使用此语法显式声明一个变量

function foo(?Type $t) {
}

这将导致

$this->foo(new Type()); // ok
$this->foo(null); // ok
$this->foo(); // error

所以,如果你想要一个可选参数,你可以遵循约定Type $t = null,而如果你需要让一个参数同时接受null它的类型,你可以遵循上面的例子。

你可以在这里阅读更多。


PHP 7.0 或更早版本

您必须添加一个默认值,例如

function foo(Type $t = null) {

}

这样,您可以传递一个空值。

这记录在手册中关于类型声明的部分中:

NULL如果参数的默认值设置为 ,则声明可以接受值NULL

于 2013-01-29T13:34:31.110 回答
36

从 PHP 7.1 开始,可以使用可空类型,作为函数返回类型和参数。该类型?T可以具有指定 TypeT或的值null

因此,您的函数可能如下所示:

function foo(?Type $t)
{

}

只要您可以使用 PHP 7.1,就应该优先使用这种表示法function foo(Type $t = null),因为它仍然强制调用者显式指定参数的参数$t

于 2016-11-09T08:55:05.210 回答
13

尝试:

function foo(Type $t = null) {

}

查看PHP 函数参数

于 2013-01-29T13:33:42.650 回答
7

从 PHP 8.0(2020 年 11 月 26 日发布)开始,您还可以使用可为空的联合类型

这意味着您可以传递Typenull作为参数值传递:

function foo(Type|null $param) {
    var_dump($param);
}

foo(new Type()); // ok : object(Type)#1
foo(null);       // ok : NULL

阅读有关联合类型的更多信息。

于 2021-02-27T20:24:17.203 回答
6

正如已经提到的其他答案,这只有在您指定null为默认值时才有可能。

但是最干净的类型安全的面向对象解决方案是NullObject

interface FooInterface
{
    function bar();
}
class Foo implements FooInterface
{
    public function bar()
    {
        return 'i am an object';
    }
}
class NullFoo implements FooInterface
{
    public function bar()
    {
        return 'i am null (but you still can use my interface)';
    }
}

用法:

function bar_my_foo(FooInterface $foo)
{
    if ($foo instanceof NullFoo) {
        // special handling of null values may go here
    }
    echo $foo->bar();
}

bar_my_foo(new NullFoo);
于 2013-01-29T13:43:34.910 回答