使用类型提示时无法传递null参数

时间:2013-01-29 13:31:44

标签: php type-hinting

以下代码:

<?php

    class Type {

    }

    function foo(Type $t) {

    }

    foo(null);

?>

在运行时失败:

PHP Fatal error:  Argument 1 passed to foo() must not be null

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

5 个答案:

答案 0 :(得分:259)

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及其类型,你可以按照上面的例子。

您可以阅读更多here


PHP 7.0或更早版

您必须添加默认值,例如

function foo(Type $t = null) {

}

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

本手册中有关Type Declarations

的部分对此进行了说明
  

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

答案 1 :(得分:29)

从PHP 7.1开始,nullable types可用,作为函数返回类型和参数。类型?T可以包含指定类型Tnull的值。

所以,你的功能可能如下所示:

function foo(?Type $t)
{

}

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

答案 2 :(得分:10)

尝试:

function foo(Type $t = null) {

}

查看PHP function arguments

答案 3 :(得分:4)

正如其他已经提到的答案一样,只有在指定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);

答案 4 :(得分:4)

自 PHP 8.0(2020 年 11 月 26 日发布)起,您还可以使用 nullable union types

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

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

阅读有关 union types 的更多信息。