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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With