In PHP, object handling mechanisms can appear enigmatic, especially when it comes to copying objects. Let's delve into a common misconception to uncover the truth.
In PHP 5 and above, objects are inherently passed by reference. This means that any changes made to an object within a function affect the original object outside the function. This is unlike passing by value, where a copy of the object is created.
The mere act of assigning an object to another variable, as exemplified by $c = $a, does not create a new copy of the object. Both variables, $a and $c, reference the same underlying object.
The provided code snippet demonstrates the impact of passing an object by reference:
<?php class A { public $b; } function set_b($obj) { $obj->b = "after"; } $a = new A(); $a->b = "before"; $c = $a; set_b($a); print $a->b; // Output: 'after' print $c->b; // Output: 'after' ?>
As expected, both $a and $c print 'after', revealing that the changes made within set_b() are reflected in both variables.
To create a genuine copy of an object, PHP provides the 'clone' operator. By utilizing this operator, you can create a new object that is independent of the original object:
$objectB = clone $objectA;
In this example, $objectB becomes a separate instance of the same class as $objectA, but with its own independent state.
In PHP, objects are passed by reference, except for everything else. The 'clone' operator offers a means of creating true copies of objects when necessary. Understanding these concepts is crucial for avoiding unexpected object behavior and ensuring clear and maintainable code.
The above is the detailed content of How Does PHP Handle Object Passing and Copying?. For more information, please follow other related articles on the PHP Chinese website!