Home >Backend Development >PHP Tutorial >How to Create Independent Object Copies in PHP Using the Clone Operator?
Creating an Object Copy in PHP
PHP objects are inherently passed by reference, making the assignment of objects simply allocate another reference to the original object. To resolve this issue and create independent object copies, PHP provides the clone operator.
Reason for Passing by Reference
In PHP, objects are effectively references to areas of memory containing the object's data. Passing by reference ensures that any modifications made to the object within the function are reflected in the original object, preserving the original intent of object-oriented programming.
Operator for Object Cloning
The clone operator is specifically designed for creating a copy of an object. By using $clonedObject = clone $originalObject, a new object is created with identical properties and values to the original object. The cloned object is a completely independent entity, and any changes made to either object will not affect the other.
Example Usage
Consider the following example:
class A { public $b; } function set_b($obj) { $obj->b = "after"; } $a = new A(); $a->b = "before"; $c = $a; // Assignment creates another reference to $a set_b($a); print $a->b; // Outputs "after" print $c->b; // Also outputs "after"
In this example, assigning $a to $c creates a reference to the same object. When set_b($a) is called, the changes are made to the original object, affecting both $a and $c.
To achieve the desired result, clone can be used as follows:
$a = new A(); $a->b = "before"; $c = clone $a; // Creates an independent copy of $a set_b($a); print $a->b; // Outputs "after" print $c->b; // Outputs "before" (not affected by changes to $a)
In this case, $c is a separate object that is not affected by modifications made to $a.
The above is the detailed content of How to Create Independent Object Copies in PHP Using the Clone Operator?. For more information, please follow other related articles on the PHP Chinese website!