可捕获的致命错误:传递给Foo::bar()的参数1必须实现接口BazInterface,给定null


Catchable Fatal Error: Argument 1 passed to Foo::bar() must implement interface BazInterface, null given

在某些情况下,当您覆盖一个具有以下类型提示输入参数的方法时:

class FooParent
{
    public function bar(BazInterface $baz)
    {
        // ...
    }
}

并且您希望允许将null值作为输入参数进行传递。

如果删除接口类型提示

class Foo extends FooParent
{
    public function bar($baz)
    {
        // ...
    }
}

你会得到这样的错误:

Fatal error: Declaration of Foo::bar() must be compatible with that of FooParent::bar()

如何在不更改父类的情况下允许null值?

这是一个真实的例子,因为父类可以是第三方库或框架的一部分,所以不能更改它。

解决方案是在输入参数中添加默认的null值,如下所示:

class Foo extends FooParent
{
    public function bar(BazInterface $baz = null)
    {
        // ...
    }
}

这不是我所期望的,因为默认值会为变量指定默认值,如果没有提供,我也没想到它会影响允许的输入。但我在http://php.net/manual/en/language.oop5.typehinting.php,所以我决定在这里记录它。希望有人会发现它有用。