note 86093 deleted from language.oop5.cloning by cmb
| From: | cmb@php.net | Date: | Sun, 10 Jul 2016 20:09:14 +0000 |
| Subject: | note 86093 deleted from language.oop5.cloning by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-205951@lists.php.net to get a copy of this message | ||
Note Submitter: wbcarts at juno dot com
----
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; // this is the property I'm trying to clone
protected static $idCount = 0; // used to increment ID numbers
protected $id; // each Soldier will have a unique 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 . ']';
}
}
# create the General and the Cloned Army
$general = new Soldier();
$platoon = array();
for($i = 0; $i < 250; $i++) $platoon[] = new Soldier();
# issue commands, then check what soldiers are doing
$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]