Pissameise
Pissameise

Reputation: 3

PHP redundant typehinting on default null and ?type

public function foo(?myObject $object = null)
    // Do something

This seems to be redundant: Using typehint-"?" and set the default value to null? May I expect different results on different ways of executing this method?

Upvotes: 0

Views: 197

Answers (2)

Adam Wądołkowski
Adam Wądołkowski

Reputation: 322

according to the php 7 documentation, when you have it

public function foo (?myObject $object)
{
}

you have to override the null parameter when the function is called - otherwise there will be an error.

$this->foo(null); // it is ok
$this->foo(); // You have error

in php 5.x, the entry is correct

public function foo ($object = null)
{
}

then you can call the function without having to explicitly pass the null paramater

$this->foo();

If you do not want to pass null to php7 functions, you can use the connections php5 and php7 - for example

public function foo (?myObject $object = null)
{
}

then you can use the method call without having to pass a parameter

$this->foo();

I think that thes (last) solution are impractical and I recommend choosing one of the solutions with php5.x or php7 (no mixing their).

Upvotes: 1

thisal selaka
thisal selaka

Reputation: 37

Another way to pass a null value.

function foo(?Type $t) {
    }


$this->foo(new Type()); // ok
$this->foo(null); // ok
$this->foo(); // error

Upvotes: 0

Related Questions