Cannot pass null argument when using type hinting

Abdullah picture Abdullah · Jan 29, 2013 · Viewed 77.9k times · Source

The following code:

<?php

    class Type {

    }

    function foo(Type $t) {

    }

    foo(null);

?>

failed at run time:

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

Why is it not allowed to pass null just like other languages?

Answer

DonCallisto picture DonCallisto · Jan 29, 2013

PHP 7.1 or newer (released 2nd December 2016)

You can explicitly declare a variable to be null with this syntax

function foo(?Type $t) {
}

this will result in

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

So, if you want an optional argument you can follow the convention Type $t = null whereas if you need to make an argument accept both null and its type, you can follow above example.

You can read more here.


PHP 7.0 or older

You have to add a default value like

function foo(Type $t = null) {

}

That way, you can pass it a null value.

This is documented in the section in the manual about Type Declarations:

The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.