以下代码:

class Type {

}

function foo(Type $t) {

}

foo(null);

运行时失败:

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

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


当前回答

在我的情况下,问题是本机“修剪”函数,不接受null。 让我们假设你有这样的代码:

if (trim($tables) != '') 
{
 //code 
} 

PHP8会抛出这个错误;所以如果你正在处理遗留代码,我建议你创建一个自定义的“修剪”函数,就像这个,让它工作得更快。

  public function custom_trim(?string $value)
  {
    return trim($value ?? '') ;
  } 

我真的很讨厌这个从7.4到8的变化

其他回答

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值。

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

Try:

function foo(Type $t = null) {

}

查看PHP函数参数。

在我的情况下,问题是本机“修剪”函数,不接受null。 让我们假设你有这样的代码:

if (trim($tables) != '') 
{
 //code 
} 

PHP8会抛出这个错误;所以如果你正在处理遗留代码,我建议你创建一个自定义的“修剪”函数,就像这个,让它工作得更快。

  public function custom_trim(?string $value)
  {
    return trim($value ?? '') ;
  } 

我真的很讨厌这个从7.4到8的变化

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

这意味着你可以将Type或null作为参数值:

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

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

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