Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

In this lesson you will learn the difference between a shallow and a deep copy in PHP so you can avoid surprising bugs when duplicating objects. This is for anyone searching for "PHP clone how to use".

PHP arrays are copied automatically on assignment, but objects are not. A shallow copy of an object (clone) duplicates only the outermost layer; any nested objects inside remain shared with the original.

The sample code duplicates a Person object with clone $original and then changes the nested part (address->city) on the copy - and $original changes too. The key detail is that the object holds another object inside it.

A common stumbling block for beginners is that arrays and objects behave fundamentally differently when copied. A plain assignment (=) copies an array, but for an object it only creates another name for the same thing, so duplicating one always requires clone.

This is the classic cause of the bug where "I copied it, but the original changed too". It is an important piece of PHP behaviour to keep in mind.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)