Cannot pass null argument when using hinting type

The following code:

<?php class Type { } function foo(Type $t) { } foo(null); ?> 

failed at runtime:

 PHP Fatal error: Argument 1 passed to foo() must not be null 

Why is it not allowed to pass null in the same way as other languages?

+83
php type-hinting
Jan 29 '13 at 1:31 on
source share
4 answers

You need to add a default value like

 function foo(Type $t = null) { } 

That way you can pass it a null value.

This is described in the section on Type Declarations :

A declaration may be accepted for accepting NULL values โ€‹โ€‹if the default value for the parameter is set to NULL .

From PHP 7.1 (released December 2, 2016) you can explicitly declare a variable as NULL with this syntax

 function foo(?Type $t) { } 

this will lead to

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

So, if you need an extra argument, you can follow the Type $t = null convention, whereas if you need to make an argument that accepts both NULL and its type, you can follow the example above.

You can read it here.

+152
Jan 29 '13 at 13:34
source share

Starting with PHP 7.1, nullable types are available for both return function types and parameters. The type ?T can have values โ€‹โ€‹of the specified type T or null .

So your function might look like this:

 function foo(?Type $t) { } 

Once you can work with PHP 7.1, this notation should be preferable to function foo(Type $t = null) , because it still forces the caller to explicitly specify an argument for the $t parameter.

+9
Nov 09 '16 at 8:55
source share

Try:

 function foo(Type $t = null) { } 

Check the arguments to the PHP function .

+7
Jan 29 '13 at 13:33
source share

As already mentioned, this is only possible if null specified as the default value.

But the cleanest object-oriented solution would be NullObject :

 interface FooInterface { function bar(); } class Foo implements FooInterface { public function bar() { return 'i am an object'; } } class NullFoo implements FooInterface { public function bar() { return 'i am null (but you still can use my interface)'; } } 

Using:

 function bar_my_foo(FooInterface $foo) { if ($foo instanceof NullFoo) { // special handling of null values may go here } echo $foo->bar(); } bar_my_foo(new NullFoo); 
+5
Jan 29 '13 at 13:43
source share



All Articles