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

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


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:

$objectB = clone $objectA;

Also, it's just objects that are passed by reference, not everything as you've said in your question...


The answers are commonly found in Java books.

  1. 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.

  2. 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:

class MyClass {  private $someObject;  public function __construct() {    $this->someObject = new SomeClass();  }  public function __clone() {    $this->someObject = clone $this->someObject;  }}

Now you can do cloning:

$bar = new MyClass();$foo = clone $bar;