tags:

views:

64

answers:

2

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?

+8  A: 

This is stated pretty clearly in the PHP manual on typehinting:

Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

zerocrates
Added link to relevant manual page
Peter Bailey
+1 looks like a behaviour to rely on. It would still be nice to find out whether there is some kind of "null" DateTime Object.
Pekka
@zerocrates: Thanks. Not only it's a documented behaviour—it's also explained in the chapter you'd expect it to be. I feel like a rookie <:-)
Álvaro G. Vicario
+1  A: 

To me your example looks like inside the Item objects there will be a check if the parameter was null or a DateTime object (if/else). I would remove that responsibility away from the Item objects into a custom DateTime, eg by extending DateTime. This MyDateTime would be responsible for knowing if the date is 'since the beginning of times' or not. There's no need for Item to do this.

koen
The idea is good but I prefer to omit such extra complexity layer by now. (The actual code doesn't really make a heavy use of dates.)
Álvaro G. Vicario