phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


OOP Pattern - Singleton: Using One Instance

Tag: oop, pattern, singleton, instance   Category: PHP Classes
post: 21 Feb 2008 read: 659


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

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


619
posting