PHP 5 Cloning an object
Copying of an object
When you assign an object to a variable, then it will copy by reference of the object, not by value. That means if you change the main object value the copied object value will be affected.
Syntax of copying object
$y = $x;
If you do this, $x and $y both print the same object. If any changes you make to the properties of object $y will automatically be made to object $x.
Example of copying object
<?php class Clone1 { public $a; private $b; function __construct($x, $y) { $this->a = $x; $this->b = $y; } } $a = new Clone1("Java" , "PHP"); $b = $a; //Copy of the object print_r($a); echo "
"; $a->a = " Operating System "; print_r($a); echo "
"; print_r($b) ?>
Output
Clone1 Object ( [a] => Java [b:Clone1:private] => PHP )
Clone1 Object ( [a] => Operating System [b:Clone1:private] => PHP )
Clone1 Object ( [a] => Operating System [b:Clone1:private] => PHP )
In the above example, $a is the object of Clone1 class and copy the reference of an object by using the assignment operator (line no 19). You can see the changes of the program after assigning the value of $a to the $b.
Download Copy of object script
Example of copying object
<?php class Clone1 { public $name; function __construct($z) { $this->name = $z; } function display() { echo $this->name; } } $a = new Clone1("Audi"); echo "Before modification:
"; $a->display(); $b=$a; $a->name="BMW"; echo"
after modification"; echo "
Using object a
"; $a->display(); echo "
Using object b
"; $b->display(); ?>
Output
Before modification:
Audi
after modification
Using object a
BMW
Using object b
BMW
You can the more clear result in the above example.
Download Copy Object Script
Clone keyword
If you want to make a copy of an object or you want to create objects by value in PHP, you need to clone it with the clone keyword like this.
Cloning of an object is also known as shallow copy.
Syntax of cloning object
$y = clone $x;
Example of clone keyword
<?php class Clone1 { public $a; function __construct($z) { $this->a = $z; } } $obj = new Clone1("Java" , "PHP"); $obj1 = $obj; //Copy of the object $obj2= clone $obj; print_r($obj); echo "
"; $obj->a = " Operating System "; print_r($obj); echo "
"; print_r($obj1); echo "
"; print_r($obj2) ?>
Output
Clone1 Object ( [a] => Java )
Clone1 Object ( [a] => Operating System )
Clone1 Object ( [a] => Operating System )
Clone1 Object ( [a] => Java )
In the above example, $obj is the object of Clone1 class, $obj is the copy of $obj and $obj2 is the clone of object $obj that means if you change the property of the class using this object does not affect the $obj2.