PHP Registry Pattern Step By Step Tutorial - Part 2: This is a variation of registry pattern implementation. Any instance would need access to same array.
see line 11: $this->_store =& $GLOBALS['REGISTRY_STORE']; reference operator binds global array to instance variable $store. This is the key to monostate implementation. Each time $this->_store is used, have impact to global variable.
<?php
define('REGISTRY_STORE','__registry_store_key__');
class CarRegistry{
var $_store;
function CarRegistry(){
if(!array_key_exists(REGISTRY_STORE, $GLOBALS)
|| !is_array($GLOBALS['REGISTRY_STORE'])){
$GLOBALS['REGISTRY_STORE'] = array();
}
$this->_store =& $GLOBALS['REGISTRY_STORE'];
}
function set($key, $obj){
$this->_store[$key] = $obj;
}
function get($key){
if(array_key_exists($key, $this->_store)){
return $this->_store[$key];
}
}
function &getInstance(){
static $instance = array();
if (!$instance){
$instance[0] =& new CarRegistry;
return $instance[0];
}else{
echo "error";
}
}
function test(){
print($this->store);
}
}
// TEST IT
$reg =& CarRegistry::getInstance();
$key = 'honda';
$value = array('Jazz', 'Stream');
$reg->set($key,$value);
$key = 'nissan';
$value = array('Teranno', 'Livina');
$reg->set($key,$value);
echo "Honda: ".implode(", ",$reg->get('honda'));
echo "</br>";
echo "Nissan: ".implode(", ",$reg->get('nissan'));
echo "</br>";
// show mirror
print_r($GLOBALS['REGISTRY_STORE']);
// OUTPUT
// Honda: Jazz, Stream
// Nissan: Teranno, Livina
// Array ( [honda] => Array ( [0] => Jazz
// [1] => Stream )
// [nissan] => Array ( [0] => Teranno
// [1] => Livina ) )
?>