Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a null DateTime to php function

Tags:

php

datetime

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?

like image 452
harryg Avatar asked Feb 26 '26 07:02

harryg


1 Answers

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.

like image 74
pcmoreno Avatar answered Feb 28 '26 21:02

pcmoreno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!