Copying an Object passes Object by Reference?!
Copying an Object passes Object by Reference?!
am 18.01.2008 18:57:19 von jerrygarciuh
I discovered this by accident today. How should I get an object's
data into another variable and make modifications without affecting
the original object?
// Example of problem
// here is x, a simple object
class O {}
$x = new O;
$x->name = "old";
$x->sex = "male";
O Object
(
[name] => old
[sex] => male
)
// moving x to y
$y = $x;
// modifying y alters x
$y->sex = "female";
$y->name = "new";
print_r($x);
O Object
(
[name] => new
[sex] => female
)
Re: Copying an Object passes Object by Reference?!
am 18.01.2008 19:13:05 von luiheidsgoeroe
On Fri, 18 Jan 2008 18:57:19 +0100, jerrygarciuh
wrote:
> I discovered this by accident today. How should I get an object's
> data into another variable and make modifications without affecting
> the original object?
Since PHP5, objects are always passed (& assigned) by reference. Use the
'clone' keyword if you need a clone, and you can even use the magic
__clone() method to alter an object on clone (possibly clone objects in
the properties too etc.).
--
Rik Wasmus
Re: Copying an Object passes Object by Reference?!
am 18.01.2008 19:14:02 von Michael Fesser
..oO(jerrygarciuh)
>I discovered this by accident today. How should I get an object's
>data into another variable and make modifications without affecting
>the original object?
Clone it:
$foo = new Object();
$bar = clone $foo;
http://www.php.net/manual/en/language.oop5.cloning.php
Micha
Re: Copying an Object passes Object by Reference?!
am 18.01.2008 19:45:22 von jerrygarciuh
On Jan 18, 12:14 pm, Michael Fesser wrote:
> .oO(jerrygarciuh)
>
> >I discovered this by accident today. How should I get an object's
> >data into another variable and make modifications without affecting
> >the original object?
>
> Clone it:
>
> $foo = new Object();
> $bar = clone $foo;
>
> http://www.php.net/manual/en/language.oop5.cloning.php
>
> Micha
Thanks Micha!
JG
Re: Copying an Object passes Object by Reference?!
am 18.01.2008 19:45:41 von jerrygarciuh
On Jan 18, 12:13 pm, "Rik Wasmus" wrote:
> On Fri, 18 Jan 2008 18:57:19 +0100, jerrygarciuh
> wrote:
>
> > I discovered this by accident today. How should I get an object's
> > data into another variable and make modifications without affecting
> > the original object?
>
> Since PHP5, objects are always passed (& assigned) by reference. Use the
> 'clone' keyword if you need a clone, and you can even use the magic
> __clone() method to alter an object on clone (possibly clone objects in
> the properties too etc.).
> --
> Rik Wasmus
Thanks Rik!
JG