It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.
Here's a simple, contrived proof:
<?php
class A {
public $b;
}
function set_b($obj) { $obj->b = "after"; }
$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.
set_b($a);
print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'
?>
In both print cases I am getting 'after'
So, how do I pass $a to set_b() by value, not by reference?
According to the docs (http://ca3.php.net/language.oop5.cloning):
The answers are commonly found in Java books.
cloning: If you don't override clone method, the default behavior is shallow copy. If your objects have only primitive member variables, it's totally ok. But in a typeless language with another object as member variables, it's a headache.
serialization/deserialization
$new_object = unserialize(serialize($your_object))
This achieves deep copy with a heavy cost depending on the complexity of the object.
According to previous comment, if you have another object as a member variable, do following:
Now you can do cloning:
This code help clone methods
I was doing some testing and got this:
In this example we will create iPhone class and make exact copy from it by cloning