The __clone Method
The __clone
method is automatically called when using the clone operator.
It allows you to define custom copying logic for the object. By default, PHP
performs shallow copying of all object properties. The __clone method is useful
when you need to implement deep copying or change the behavior during cloning.
Syntax
public function __clone(): void
Example
Let's implement basic object cloning:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function __clone() {
echo 'Object cloned';
}
}
$user1 = new User('John');
$user2 = clone $user1;
?>
Code execution result:
'Object cloned'
Example
Let's implement deep copying of an object with nested objects:
<?php
class Address {
public $city;
public function __construct($city) {
$this->city = $city;
}
}
class User {
public $name;
public $address;
public function __construct($name, $city) {
$this->name = $name;
$this->address = new Address($city);
}
public function __clone() {
$this->address = clone $this->address;
}
}
$user1 = new User('John', 'New York');
$user2 = clone $user1;
$user2->address->city = 'Boston';
echo $user1->address->city;
?>
Code execution result:
'New York'
Example
Let's add a unique identifier when cloning:
<?php
class Product {
public $id;
public $name;
public function __construct($name) {
$this->id = uniqid();
$this->name = $name;
}
public function __clone() {
$this->id = uniqid();
}
}
$product1 = new Product('Laptop');
$product2 = clone $product1;
echo $product1->id . ' ' . $product2->id;
?>
Code execution result (example):
'5f1a2b3c 5f1a2b3d'
See Also
-
the
__construct
method,
which is the object constructor