我有一个处理日期的类方法:
public function setAvailability(DateTime $start,DateTime $end){ }
由于项目可用性可以具有下限,上限,两者或无,我想使setAvailability()接受NULL值.但是,NULL常量违反了类型提示:
$foo->setAvailability(NULL,$end);
触发:
Catchable fatal error: Argument 1
passed to Foo::setAvailability() must be an
instance of DateTime,null given
而且,据我所知,我没有一个没有价值的DateTime实例. (我可以吗?)
出于某种原因我无法掌握,这似乎是有效的:
public function setAvailability(DateTime $start=NULL,DateTime $end=NULL){ } ... $foo->setAvailability(NULL,$end);
但它看起来像一个纯粹机会的黑客.
在PHP类中如何处理未定义的日期?
这在
the PHP manual on typehinting年很清楚地说明了:
原文链接:https://www.f2er.com/php/132032.htmlFunctions 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.