The __clone() magic method is used to clone a class using a same new instance.

If you notice closely, when we create a new object of class likeso, $class = new DevPeel(); a new object created of a classes and includes a index flag with the object.

For example, lets create two objects of similar class.

class DevPeel
{
	//
}

$class = new DevPeel();
$classTwo = new DevPeel();

var_dump($class);
var_dump($classTwo);

& the output, if you look closely are two separate instances of the DevPeel class.

object(DevPeel)#1 (0) {
}
object(DevPeel)#2 (0) {
}

We can also achieve it using clone helper function in PHP likeso,

$class = new DevPeel();
$classTwo = clone $class;

But the question here must be why do we actually feel the need of cloning a class object.

Another Example

class User
{
     public $email = 'usama@devpeel.com';
}

$user = new User();
$oldUser = clone $user;
$user->email = 'contact@devpeel.com';
var_dump("User email was changed from: {$oldUser->email} to {$user->email}");

This is a simple User object and we’ve cloned the User in case of keeping track of any changes.

Another Example

Now let’s move forward and look what __clone() magic method does actually.

class Address
{
	public $line;

	public function __construct($line){
		$this->line = $line;
	}
}

class User
{
	protected $address;
	public function __construct(Address $address){
		$this->address = $address;
	}

	public function __clone(){
		$this->address = clone $this->address;
	}
}

$address = new Address('street 9, alfa');
$user = new User($address);
$clonedUser = clone $user;

$address->line = 'A new address line';
var_dump($user);
var_dump($clonedUser);

If you look at the above example, when we update the new $address->line without cloning it, it shows this updated line only and after we’ve added __clone() magic method to internally clone the address for us, it keeps a copy of the addresses.

This output as follows:

object(User)#2 (1) {
  ["address":protected]=>
  object(Address)#1 (1) {
    ["line"]=>
    string(18) "A new address line"
  }
}
object(User)#3 (1) {
  ["address":protected]=>
  object(Address)#4 (1) {
    ["line"]=>
    string(14) "street 9, alfa"
  }
}

Also note that the __clone() magic method comes handy very occasionally & not normally used within development. Within PHP, you need to have some specific use-case for utilizing __clone() magic method.

You may also Like