OOP Pattern - Singleton: Using One Instance
PHP Singleton Pattern Step By Step Tutorial - Part 2: We have learned how to make a class can be accessed by certain method. Now, we will see how to implement singleton pattern.
I use $GLOBAL for handle PHP4 limited. You can also use other like $_SESSION.
<?php
class CarSingleton {
var $instance = NULL;
var $place = "#1";
function CarSingleton($fromGetInstance = false){
if(M_E != $fromGetInstance){
trigger_error('do not instantiate
directly');
}
}
function &washCar(){
if (!$GLOBALS[$load]){
if(!$this->instance){
$this->instance = new CarSingleton(M_E);
$GLOBALS[$load] = "full";
return $this->instance;
}
}else{
return NULL;
}
}
function getPlace(){
return $this->place;
}
function finish(){
$GLOBALS[$load] = NULL;
}
}
class WashingCar{
var $washedCar;
var $havePlace;
function washing(){
$this->washedCar = CarSingleton::washCar();
if ($this->washedCar == NULL){
$this->havePlace = FALSE;
}else{
$this->havePlace = TRUE;
}
}
function getPlace(){
if ($this->havePlace == TRUE){
return $this->washedCar->getPlace();
}else{
return "Sorry, it is full!";
}
}
function finish(){
$this->washedCar->finish();
}
}
// TEST IT
$obj1 = new WashingCar;
$obj2 = new WashingCar;
$obj1->washing();
echo "obj1 want to wash his car";
echo "</br>";
echo "obj1 get place: ";
echo $obj1->getPlace();
echo "</br>";
$obj2->washing();
echo "obj2 want to wash his car";
echo "</br>";
echo "obj2 get place: ";
echo $obj2->getPlace();
echo "</br>";
$obj1->finish();
echo "obj1's car is finish";
echo "</br>";
$obj2->washing();
echo "obj2 want to wash his car";
echo "</br>";
echo "obj2 get place: ";
echo $obj2->getPlace();
// OUTPUT WILL BE LIKE THIS
//obj1 want to wash his car
//obj1 get place: #1
//obj2 want to wash his car
//obj2 get place: Sorry, it is full!
//obj1's car is finish
//obj2 want to wash his car
//obj2 get place: #1
?>
| Series this article: OOP Pattern - Singleton: Enter Point OOP Pattern - Singleton: Using One Instance Tag: oop, pattern, singleton, instance Category: PHP Classes Post : February 21st 2008 Read: 1,532 blog comments powered by Disqus |
