2

I have a function in php that I want to accept either a DateTime object or null. E.g.

function foo(DateTime $aDate){
   if ($aDate == null){
       echo "You passed a null variable";
   } else {
       echo "You passed the date " . $aDate->format('Y-m-d');
   }
}

Trouble is, because the function expects a DateTime object it flips out when I pass null to it and gives an error:

Catchable fatal error: Argument 1 passed to foo() must be an instance of DateTime, null given,...

How can I pass null to the function and avoid this error?

4 Answers 4

7

add a ? to the type hint.

    function foo(?DateTime $aDate){
        if ($aDate == null){
            echo "You passed a null variable";
        } else {
            echo "You passed the date " . $aDate->format('Y-m-d');
        }
    }

This way only an explicit NULL or DateTime are allowed.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this is only possible in PHP >= 7.1.
I was just too late to edit: The file where the function is called from must have declare(strict_types = 1); as its first statement, or it won't be enforced.
6

Change from this:

function foo(DateTime $aDate){

To this:

function foo($aDate){

But if you still want to make sure the object passed is a DateTime object you can do this:

function foo(DateTime $aDate = null){

See here for more examples of Type Hinting.

5 Comments

Interesting that it doesn't allow null with type hinting. Part of me feels it should.
OK so what is the point in putting DateTime in the paramater list of the function if you can still pass a DateTime without it?
@JasonMcCreary Ahh found the solution!
Yeah, the update makes more sense. I would like to force passing either a DateTime or null.
This is possible in PHP 7.1 and above, see @pcmoreno's answer. IMO, his answer should be the accepted one now.
3

Make $aDate optional.

function foo(DateTime $aDate = null) {
    if($aDate) {
        //parse date
    } else {
        //null given
    }
}

Comments

1

The way to do it is to assign a default value in the function declaration:-

function foo(DateTime $aDate = null){
   if (!$aDate){
       echo "You passed a null variable";
   } else {
       echo "You passed the date " . $aDate->format('Y-m-d');
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.