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?

harryg
  • 23,311
  • 45
  • 125
  • 198

4 Answers4

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.

pcmoreno
  • 101
  • 2
  • 5
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.

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
3

Make $aDate optional.

function foo(DateTime $aDate = null) {
    if($aDate) {
        //parse date
    } else {
        //null given
    }
}
kwolfe
  • 1,663
  • 3
  • 17
  • 27
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');
   }
}
vascowhite
  • 18,120
  • 9
  • 61
  • 77