The __clone method helps you make a copy of an object. It lets you control what happens when you copy an object.
0
0
__clone for object copying in PHP
Introduction
When you want to create a new object that starts with the same data as an existing one.
When you need to copy an object but want to change some parts during copying.
When your object has other objects inside it and you want to copy those too.
When you want to avoid changing the original object by mistake after copying.
Syntax
PHP
class ClassName { public function __clone() { // code to run when object is cloned } }
The __clone method is called automatically when you use clone keyword.
You can use __clone to customize the copying process, like copying inner objects.
Examples
This example shows a simple clone. Changing the copy's name does not affect the original.
PHP
<?php class Person { public $name; public function __clone() { // no special action needed } } $p1 = new Person(); $p1->name = "Alice"; $p2 = clone $p1; $p2->name = "Bob"; print $p1->name . "\n"; // Alice print $p2->name . "\n"; // Bob ?>
This example shows how to copy inner objects by cloning them inside
__clone. This avoids shared inner objects.PHP
<?php class Address { public $city; } class Person { public $name; public $address; public function __clone() { // Make a deep copy of address $this->address = clone $this->address; } } $person1 = new Person(); $person1->name = "Alice"; $person1->address = new Address(); $person1->address->city = "Paris"; $person2 = clone $person1; $person2->address->city = "London"; print $person1->address->city . "\n"; // Paris print $person2->address->city . "\n"; // London ?>
Sample Program
This program creates a book object, copies it using clone, and changes the copy's title. The original stays the same.
PHP
<?php class Book { public $title; public $author; public function __clone() { // No special action needed here } } $book1 = new Book(); $book1->title = "PHP Basics"; $book1->author = "John"; $book2 = clone $book1; $book2->title = "Advanced PHP"; print "Book 1 title: " . $book1->title . "\n"; print "Book 2 title: " . $book2->title . "\n"; ?>
OutputSuccess
Important Notes
Using clone creates a shallow copy by default. Use __clone to make deep copies if needed.
If you don't define __clone, PHP still copies the object but you can't customize the process.
Summary
__clone runs automatically when you copy an object with clone.
Use __clone to copy inner objects or change data during copying.
Cloning helps keep original and copy separate so changes don't mix up.