<?php
class CopyClass{
public $name;
}
$first= new CopyClass();
$first->name="Number 1";
$second= clone $first;
echo "first = ".$first->name."<br>";
$second->name="Number 2";
echo "first = " . $first->name . "<br>";
echo "second = " . $second->name . "<br>";
If you want a record of the state of the object after each property is added you can clone the object after each addition.
$object->id = "1";
$object->fname = "Ray";
$object->lname = "Paseur";
$object->work = "Programmer";
$object->func = "testData";
$arr[] = /*clone*/ $object;
$object->id = "2";
$object->fname = "John";
$object->lname = "James";
$object->work = "Student";
$arr[] = /*clone*/ $object;
$object->id = "3";
$object->fname = "Dave";
$object->lname = "Baldwin";
$object->work = "Expert";
$arr[] = /*clone*/ $object;
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html
The real-world example might exist in an environment where an object gets mutated and you need a second copy of the object. Perhaps you call a method after property #1 is added to the object, then another method after property #2, etc. If you want a record of the state of the object after each property is added you can clone the object after each addition.
You can also nullify the clone() method, as in a Singleton design pattern.
Open in new window