How do I create a copy of an object in PHP?

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?

9 Answers
9

Leave a Comment