Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hinting and optional attributes in PHP

Tags:

oop

php

datetime

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?

like image 773
Álvaro González Avatar asked May 05 '10 15:05

Álvaro González


1 Answers

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.

like image 65
John Flatness Avatar answered Sep 17 '22 16:09

John Flatness