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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With