What is the difference between shallow copy and deep copy

In programming, particularly in Python and other object-oriented languages, the concepts of shallow copy and deep copy are essential for managing and duplicating objects.

A shallow copy creates a new object that is a copy of the original object, but it only copies the reference pointers to the nested objects within the original. So, if you modify a nested object within the shallow copy, that change will also reflect in the original object.

A deep copy, on the other hand, creates a new object and recursively copies all objects found within the original, including all nested objects. Changes made to a deep copy do not affect the original object.

Here’s an example in PHP:

<?php class Person { public $name; public $friends; public function __construct($name, $friends) { $this->name = $name; $this->friends = $friends; } } // Original object $alice = new Person("Alice", ["Bob", "Charlie"]); // Shallow copy $shallowCopy = $alice; // Both point to the same instance // Deep copy $deepCopy = new Person($alice->name, $alice->friends); // Creates a new instance $deepCopy->friends = array_merge([], $deepCopy->friends); // Ensures separate friends array // Modify the shallow copy $shallowCopy->name = "Alicia"; $shallowCopy->friends[0] = "Bobby"; // This will affect $alice as well echo "Alice's name: " . $alice->name . "<br>"; echo "Shallow Copy's name: " . $shallowCopy->name . "<br>"; // Modify deep copy $deepCopy->name = "Alison"; $deepCopy->friends[0] = "Diana"; // This won't affect $alice echo "Alice's name: " . $alice->name . "<br>"; echo "Deep Copy's name: " . $deepCopy->name . "<br>"; ?>

shallow copy deep copy PHP objects.