Creating Object Copies in PHP
PHP handles object references in a unique way. Contrary to popular belief, objects are passed by reference, implying that assigning an object to another variable does not create a copy. This behavior becomes evident when modifying the original object after the assignment.
Example:
Consider the following PHP snippet:
class A { public $b; } function set_b($obj) { $obj->b = "after"; } $a = new A(); $a->b = "before"; $c = $a; // This line creates a reference to $a, not a copy set_b($a); print $a->b; // Output: 'after' print $c->b; // Output: 'after'
In this example, assigning $a to $c creates a reference to $a rather than a copy. When the set_b() function modifies the $a object, the changes are reflected in both $a and $c.
Solution: Using Clone
PHP 5 and later provide the clone operator to create true copies of objects. By using clone, you can pass an object by value and ensure that modifications to the original object do not affect the copy.
$objectB = clone $objectA; // Creates a copy of $objectA
Important Note:
It's worth mentioning that only objects are passed by reference in PHP. Primitive data types (such as integers, strings, and boolean values) are always passed by value.
The above is the detailed content of How Do I Create True Copies of Objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!