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

Php 可捕获的致命错误:传递给Foo::bar()的参数1必须实现接口,给定null,php,oop,types,Php,Oop,Types,在某些情况下,重写具有以下类型提示输入参数的方法: class FooParent { public function bar(BazInterface $baz) { // ... } } Fatal error: Declaration of Foo::bar() must be compatible with that of FooParent::bar() class Foo extends FooParent { public fun

在某些情况下,重写具有以下类型提示输入参数的方法:

class FooParent
{
    public function bar(BazInterface $baz)
    {
        // ...
    }
}
Fatal error: Declaration of Foo::bar() must be compatible with that of FooParent::bar()
class Foo extends FooParent
{
    public function bar(BazInterface $baz = null)
    {
        // ...
    }
}
您希望允许传递空值作为输入参数

如果删除接口类型提示

class Foo extends FooParent
{
    public function bar($baz)
    {
        // ...
    }
}
您将得到如下错误:

class FooParent
{
    public function bar(BazInterface $baz)
    {
        // ...
    }
}
Fatal error: Declaration of Foo::bar() must be compatible with that of FooParent::bar()
class Foo extends FooParent
{
    public function bar(BazInterface $baz = null)
    {
        // ...
    }
}
如何在不更改父类的情况下允许空值


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

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

class FooParent
{
    public function bar(BazInterface $baz)
    {
        // ...
    }
}
Fatal error: Declaration of Foo::bar() must be compatible with that of FooParent::bar()
class Foo extends FooParent
{
    public function bar(BazInterface $baz = null)
    {
        // ...
    }
}
这不是我所期望的,因为默认值将默认值分配给变量。如果没有提供,我不希望它影响允许的输入。但我看到了上面的示例,所以我决定在这里记录它。希望有人会觉得它有用