Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

oop

php

There are some cases when you override a method which has type hinted input parameter like this:

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

And you want to allow passing null values as input parameters.

If you remove interface type hint

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

you'll get an error like this:

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

How can you allow null values without changing the parent class?

This is a real world example since parent class can be part of the third party library or framework, so changing it is not an option.

like image 905
umpirsky Avatar asked Jul 28 '12 20:07

umpirsky


1 Answers

Solution is to add default null value to input parameter like this:

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

This is not what I expected since default value assigns default value to a variable if not provided, I didn't expect it to affect allowed input. But I saw example on http://php.net/manual/en/language.oop5.typehinting.php, so I decided to document it here. Hope someone will find it useful.

like image 155
umpirsky Avatar answered Sep 30 '22 05:09

umpirsky