Type hinting and optional attributes in PHP

Posted by Álvaro G. Vicario on Stack Overflow See other posts from Stack Overflow or by Álvaro G. Vicario
Published on 2010-05-05T15:08:40Z Indexed on 2010/05/05 15:18 UTC
Read the original article Hit count: 181

Filed under:
|
|

I have a class method that deals with dates:

public function setAvailability(DateTime $start, DateTime $end){
}

Since item availability can have lower limit, upper limit, both or none, I'd like to make setAvailability() accept NULL values as well. However, the NULL constant violates the type hinting:

$foo->setAvailability(NULL, $end);

triggers:

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

And, as far as I know, I cannot have a DateTime instance with no value. (Can I?)

For a reason I cannot grasp, this seems to work:

public function setAvailability(DateTime $start=NULL, DateTime $end=NULL){
}
...
$foo->setAvailability(NULL, $end);

But it looks like a hack that works by pure chance.

How would you deal with unset dates in PHP classes?

© Stack Overflow or respective owner

Related posts about php

Related posts about oop