The following code:
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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
PHP 7.1 or newer (released 2nd December 2016)
You can explicitly declare a variable to be
nullwith this syntaxthis will result in
So, if you want an optional argument you can follow the convention
Type $t = nullwhereas if you need to make an argument accept bothnulland its type, you can follow above example.You can read more.
PHP 7.0 or older
You have to add a default value like
That way, you can pass it a null value.
This is documented in the section in the manual about Type Declarations: