Abdullah Abdullah - 4 months ago 13
PHP Question

Cannot pass null argument when using type hinting

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

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.