我使用以下代码:
$input = new DateTime(filter_input(INPUT_GET, 'date'));
$input->modify('midnight');
echo $input->format(DateTime::RFC3339) . "'n";
$end = $input;
$end->modify('+3 hours');
echo $input->format(DateTime::RFC3339) . "'n";
echo $end->format(DateTime::RFC3339) . "'n";
这给出了以下输出:
2016-02-01T00:00:00-5:00
2016-02-01T03:00:00-5:00
2016-02-01T03:00:00-5:00
第二行的输出不应该与第一行相同吗?
根据我的理解,通过引用分配变量你需要使用$a = &$b
,所以我使用的($a = $b
)应该是按值。因此,在$end
上调用的函数也不应该修改$input
,对吗?我错过了什么?
问题是DateTime
是对象,对象总是通过引用分配。如果要按"值"分配,则必须使用克隆,如$end = clone $input;
。
以下是PHP手册中有关它的信息:http://php.net/manual/en/language.oop5.references.php