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?
Just to clarify PHP uses copy on write, so basically everything is a reference until you modify it, but for objects you need to use clone and the __clone() magic method like in the accepted answer.
In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).
You can use the 'clone' operator in PHP5 to copy objects:
Also, it's just objects that are passed by reference, not everything as you've said in your question...
If you want to fully copy properties of an object in a different instance, you may want to use this technique:
Serialize it to JSON and then de-serialize it back to Object.