Difference Between Deep Copy and Shallow Copy in PHP

Introduction

This article explains Deep Copy and Shallow Copy in PHP. Copying of data is an important task of programming. A member field in an object may be stored by value or by reference. The copying of data is done in one of the following two ways:

  • Deep Copy and
  • Shallow Copy

In a Deep Copy everything is duplicated and all values are copied into a new instance. In this case all members are stored as a reference. When there are pointers, new pointers are created to the new data. Any changes of references will not affect the referenced object of other copies of the object. Fully replicated objects are deep copied. In PHP the "Copy" keyword is performed as a Shallow Copy by default. In PHP5 all objects are assigned by reference. It calls the object's "__clone()" method.

Example

<?php

class Obj

{

    public $id;

    public $size;

    public $color;

    function __construct($id, $size, $color)

       {

        $this->id = $id;

        $this->size = $size;

        $this->color = $color;

    }

    function __clone()

        {

       $green = $this->color->green;

        $blue = $this->color->blue;

         $red = $this->color->red;

        $this->color = new Color($green, $blue, $red);

    }

}

class Color

{

    public $green;

    public $blue;

    public $red;

    function __construct($green, $blue, $red)

        {

        $this->green = $green;

        $this->blue = $blue;

        $this->red = $red;

    }

}

$color = new Color(23, 42, 223);

$obj1 = new Obj(23, "small", $color);

$obj2 = clone $obj1;

$obj2->id++;

$obj2->color->red = 255;

$obj2->size = "big";

echo "<pre>";print_r($obj1);

echo "<pre>";print_r($obj2);

?>

Output

shallow copy.jpg

A Shallow Copy copies duplicates as little as possible. A Shallow Copy copies all the values and references into a new instance. In a Shallow Copy any change of a reference member affects both the methods.

Example

<?php

class Obj

{

    public $id;

    public $size;

    public $color;

    function __construct($id, $size, $color)

       {

        $this->id = $id;

        $this->size = $size;

        $this->color = $color;

    }

}

class Color

{

    public $green;

    public $blue;

    public $red;

    function __construct($green, $blue, $red)

        {

        $this->green = $green;

        $this->blue = $blue;

        $this->red = $red;

    }

}

$color = new Color(23, 42, 223);

$obj1 = new Obj(23, "small", $color);

$obj2 = clone $obj1;

 

$obj2->id++;

$obj2->color->red = 255;

$obj2->size = "big";

 

echo "<pre>";print_r($obj1);

echo "<pre>";print_r($obj2);

?>

Output

deep copy.jpg

You will see that the id and the size is different but the color is same.


Similar Articles