在运行一些测试时,注意到检查DateInterval对象上的公共属性,即使它们包含数据也会返回false.为什么这个/我们在文档中遗漏了什么?
例:
$currentDate = new DateTime(); $targetDate = new DateTime('2015-03-05 11:11:11'); $interval = $currentDate->diff($targetDate); var_dump($interval->y); var_dump($interval->m); var_dump(isset($interval->y)); var_dump(isset($interval->m)); var_dump($interval);
将给出以下输出:
int(0) int(2) bool(false) bool(false) object(DateInterval)#3 (15) { ["y"]=> int(0) ["m"]=> int(2) ["d"]=> int(1) ["h"]=> int(9) ["i"]=> int(43) ["s"]=> int(35) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(1) ["days"]=> int(62) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) }
这绝对有趣.看一下这个:
$currentDate = new DateTime(); $targetDate = new DateTime('2015-03-05 11:11:11'); $interval = $currentDate->diff($targetDate); echo "<pre>"; //var_dump($interval); --> if you uncomment this line,it will work just fine var_dump($interval->y); var_dump($interval->m); var_dump(isset($interval->y)); var_dump(isset($interval->m));
在调用isset()之前执行var_dump($interval)会打印出正确的结果!
object(DateInterval)#3 (15) { ["y"]=> int(0) ["m"]=> int(2) ["d"]=> int(1) ["h"]=> int(9) ["i"]=> int(49) ["s"]=> int(33) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(1) ["days"]=> int(62) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) } int(0) int(2) bool(true) bool(true)
我认为你必须真正偶然发现这种语言中的一个怪癖.我无法想到与var_dump或isset或PHP的OOP实现有关,这可能会导致此行为.也许是PHP的错误报告?