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

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

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why c = $a Doesn't Copy Your Object in PHP

You might expect that assigning one object to another creates a duplicate. In many statically typed languages, this is straightforward: you create a new instance on the heap, and both variables point to distinct memory locations. If you modify $a, $c remains untouched. However, in PHP, the reality is different because of how assignment operators handle objects.

The statement $c = $a does not create a copy of the object. It creates a new variable that points to the exact same instance residing in memory. This behavior is often described as shallow copying via reference. When you pass $a to a function like set_b($obj), the parameter $obj becomes an alias for $a. Modifying $obj->b modifies $a->b instantly. Consequently, any other variable pointing to that same object instance will see the change immediately.

This fundamental behavior means that PHP objects are effectively passed by reference by default, regardless of whether you explicitly declare a parameter as &$obj or not. If your goal is to achieve true value semantics—where changes inside a function do not affect the original variable—you must use cloning or serialization techniques rather than simple assignment.

Using the Clone Keyword for Shallow Copies

To create an independent copy of an object without writing a custom serialization routine, PHP provides the clone keyword. This operator invokes the object's constructor logic again to generate a new instance and copies the property values from the original to the new instance.

$a = new A();
$a->b = "before";

// Create a shallow copy
$c = clone $a; 

set_b($a);

print $a->b; // Outputs: after
print $c->b; // Outputs: before

In this scenario, $c now points to a distinct object in memory. When set_b alters the property on $a, $c retains its original value because it is a separate entity. This is the standard way to handle immutability when dealing with mutable state inside functions.

Understanding Shallow vs. Deep Copies

While clone solves the immediate problem of variable aliasing, you must be aware of the distinction between shallow and deep copies. A shallow copy, which clone performs by default, duplicates the object's structure but not its nested objects or collections. If your class contains properties that are themselves objects, arrays, or resources, those inner structures will still share references.

class Container {
    public $item;
    
    public function __construct($val) {
        $this->item = new Item($val);
    }
}

class Item {
    public $value;
    public function __construct($v) { $this->value = $v; }
}

$container1 = new Container("original");
$container2 = clone $container1;

// Modifying the nested object affects both containers
$container1->item->value = "modified";
echo $container2->item->value; // Outputs: modified

If you require a deep copy where every nested level is duplicated, clone alone is insufficient. You would need to implement a custom cloning strategy or leverage serialization methods like serialize() and unserialize(). However, relying on serialization for performance-critical paths can be inefficient and may fail if the object contains resources that cannot be serialized.

Deep Cloning in Laravel Collections

In modern PHP development, particularly when working with collections, you might encounter scenarios where deep cloning is necessary to prevent unintended side effects. The LaravelCompany library offers utilities that simplify complex data manipulation tasks, including scenarios where you need to isolate collection states before processing.

If you are using the laravel-collection package or similar libraries, be mindful of how they handle internal references. While standard PHP objects require explicit cloning, some collection implementations provide their own methods to ensure deep copies are made when manipulating subsets or transforming data in place. Always verify whether a library's documentation specifies if its returned structures are shallow or deep copies, as this can impact your application's data integrity.

When Assignment is Actually Safe

There are cases where you intentionally want variables to share the same object instance. This is common in dependency injection scenarios where multiple services need access to a singleton configuration object. In these situations, using clone would be counterproductive. The key is understanding that $c = $a is not a bug; it is a feature designed for memory efficiency and shared state management.

When debugging issues related to unexpected data mutations, check if you have accidentally created multiple references to the same instance instead of cloning when necessary. This often happens when passing objects into helper functions or iterating over arrays of objects without accounting for reference semantics.

Our network