PHP 似乎是按引用分配,而不是按值分配
PHP Seems To Be Assigning By Reference, Not By Value
我正在使用以下代码:
$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
是对象,对象总是通过引用赋值。如果你想通过 "value" 分配,你必须使用像 $end = clone $input;
.
这样的克隆
PHP 手册中有关于它的信息:http://php.net/manual/en/language.oop5.references.php
我正在使用以下代码:
$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
是对象,对象总是通过引用赋值。如果你想通过 "value" 分配,你必须使用像 $end = clone $input;
.
PHP 手册中有关于它的信息:http://php.net/manual/en/language.oop5.references.php