You are here: PHP brain teaser « PHP Programming Language « IT news, forums, messages
PHP brain teaser

Posted by Chung Leong on 01/13/06 05:01

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
)

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация