|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2001-01-11 16:27 UTC] lgordon at idiotbrain dot com
<?php
// buggy.php
// If I leave both A1 and A2 commented out, the code works fine.
// If I uncomment A1 only, the code works as expected
// If I uncomment A2 only, the code does not work as expected
class Element
{
var $val;
function set_value($newval)
{
$this->val = $newval;
}
}
class Owner
{
var $elementArray;
function dump()
{
foreach ($this->elementArray as $index => $value)
{
print("index [$index] value [$value->val]<BR>");
}
}
}
$myOwner = new Owner();
$myOwner->elementArray[0] = new Element;
// -- A1 --
// this works as expected
$myOwner->elementArray[0]->val = 10;
// -- A2 --
// if this line is uncommented the code does not work as expected
//$myOwner->elementArray[0]->set_value(10);
print("dump myOwner<BR>");
$myOwner->dump();
print("<BR>");
print("make a copy of myOwner<BR>");
$copyOwner = $myOwner;
print("<BR>");
print("dump copyOwner<BR>");
$copyOwner->dump();
print("<BR>");
print("change copyOwner index 0 to 999999<BR>");
$copyOwner->elementArray[0]->val = 999999;
print("dump copyOwner<BR>");
$copyOwner->dump();
print("<BR>");
print("dump myOwner<BR>");
$myOwner->dump();
print("<BR>");
?>
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 02 17:00:02 2025 UTC |
The workaround that I have had to implement is doing an explicit clone method (similar to a copy constructor) and when making a copy, say $new = $old->clone(); instead of $new = $old; example implementation: class Element { var $value; function &clone() { $obj = new Element(); $obj=>value = $this->value; } } class X { var $array; function &clone() { $obj = new X(); foreach($this->array as $index => $value) { $obj->array[$index] = $value->clone(); } return $obj; } }