CLONED ARMIES? USE STATIC DATA
When I think of cloning, I always think of Star Wars "Cloned Army"... where the number of clones are in the hundreds of thousands. So far, I have only seen examples of one or two clones with either shallow, deep, or recursive references. My fix is to use the static keyword. With static, you choose the properties your objects share... and makes scaling up the number of so-called "clones" much easier.
<?php
class Soldier {
public static $status; protected static $idCount = 0; protected $id; public function __construct() {
$this->id = ++self::$idCount;
}
public function issueCommand($task) {
switch($task){
case 'Deploy Troops': self::$status = 'deploying'; break;
case 'March Forward': self::$status = 'marching forward'; break;
case 'Fire!': self::$status = 'shot fired'; break;
case 'Retreat!': self::$status = 'course reversed'; break;
default: self::$status = 'at ease'; break;
}
echo 'COMMAND ISSUED: ' . $task . '<br>';
}
public function __toString() {
return "Soldier[id=$this->id, status=" . self::$status . ']';
}
}
$general = new Soldier();
$platoon = array();
for($i = 0; $i < 250; $i++) $platoon[] = new Soldier();
$general->issueCommand('Deploy Troops');
echo $general . '<br>';
echo $platoon[223] . '<br>';
echo $platoon[12] . '<br>';
$general->issueCommand('March Forward');
echo $platoon[47] . '<br>';
echo $platoon[163] . '<br>';
$general->issueCommand('Fire!');
echo $platoon[248] . '<br>';
echo $platoon[68] . '<br>';
$general->issueCommand('Retreat!');
echo $platoon[26] . '<br>';
echo $platoon[197] . '<br>';
?>
COMMAND ISSUED: Deploy Troops
Soldier[id=1, status=deploying]
Soldier[id=225, status=deploying]
Soldier[id=14, status=deploying]
COMMAND ISSUED: March Forward
Soldier[id=49, status=marching forward]
Soldier[id=165, status=marching forward]
COMMAND ISSUED: Fire!
Soldier[id=250, status=shot fired]
Soldier[id=70, status=shot fired]
COMMAND ISSUED: Retreat!
Soldier[id=28, status=course reversed]
Soldier[id=199, status=course reversed]