PHP / CHAPTER 05
Copies, object handles, and references
IntermediatePredict which updates are shared across variables.
By the end of this chapter
- Distinguish array value copies from object sharing
- Understand explicit reference aliases
- Clear lingering foreach references
The idea
Ordinary PHP array assignment has value semantics: modifying one array’s scalar element does not change the other array. Implementations can share storage internally until mutation, but the visible behavior follows independent array values. Objects behave differently: assigning an object variable copies its object identifier, so both variables refer to the same object unless a deliberate clone is made.
An explicit & reference creates aliases for the same variable container and therefore changes the ordinary assignment story. A foreach loop by reference leaves its loop variable associated with the last element after the loop ends. unset that loop variable before reusing it. Nested objects inside copied arrays still refer to shared object instances, so describe copy depth carefully rather than promising that every assignment duplicates an entire data structure.
<?php
$a=[1,2];$b=$a;$b[0]=9;
echo $a[0],"\n";
$x=(object)["n"=>1];$y=$x;$y->n=7;
echo $x->n,"\n";1 7
The array’s scalar update is independent, while the object property update is visible through both object variables.
Try it yourself
Demonstrate independent scalar array updates and shared object updates without explicit references.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING