问题描述
这里有一个小小的预告片从一个错误中提炼出来,这让我花了很长时间才能搞清楚。以下示例中的两个函数表现为不同的
。这种差异很容易被发现。挑战
正确地解释了为什么会这样。为什么第二个函数
似乎破坏了对象的克隆副本?
示例代码:
< ;?php
//取消注释PHP 5的克隆运算符
函数Bobcat(& $ obj){
$ clone = / * clone * / $ obj;
$ obj-> attributes [''Length''] = 0;
$ obj-> ; data ="" ;;
返回$ clone;
}
函数BritneySpear(& $ obj){
$ attr =& $ obj->属性;
$ clone = / * clone * / $ obj;
$ obj-> attributes [''Length''] = 0;
$ obj-> data ="" ;;
返回$ clone;
}
$ data ="这是一个测试;
$ obj1-> attributes = array(''Length''=> strlen($ data));
$ obj1-> data = $ data;
$ clone1 = Bobcat($ obj1);
print_r($ clone1);
$ obj2-> attributes = array(''Length''=> strlen($ data));
$ obj2-> data = $ data;
$ clone2 = BritneySpear($ obj2);
print_r($ clone2);
?>
结果:
stdClass对象
(
[attributes] =>数组
(
[长度] => 14
)
[数据] = >这是一个测试
)
stdClass对象
(
[attributes] =>数组
(
[长度] => 0
)
[data] =>这是一个测试
)
Here''s a little brain teaser distilled from a bug that took me a rather
long time to figure out. The two functions in the example below behave
differently. The difference is easy to spot, of ocurse. The challenge
is correctly explaining why this is so. Why does the second function
seemingly corrupt the cloned copy of an object?
Sample code:
<?php
// uncomment the clone operator for PHP 5
function Bobcat(&$obj) {
$clone = /* clone */ $obj;
$obj->attributes[''Length''] = 0;
$obj->data = "";
return $clone;
}
function BritneySpear(&$obj) {
$attr =& $obj->attributes;
$clone = /* clone */ $obj;
$obj->attributes[''Length''] = 0;
$obj->data = "";
return $clone;
}
$data = "This is a test";
$obj1->attributes = array(''Length'' => strlen($data));
$obj1->data = $data;
$clone1 = Bobcat($obj1);
print_r($clone1);
$obj2->attributes = array(''Length'' => strlen($data));
$obj2->data = $data;
$clone2 = BritneySpear($obj2);
print_r($clone2);
?>
Result:
stdClass Object
(
[attributes] => Array
(
[Length] => 14
)
[data] => This is a test
)
stdClass Object
(
[attributes] => Array
(
[Length] => 0
)
[data] => This is a test
)
推荐答案
这篇关于PHP脑筋急转弯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!