phpeveryday.com

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


OOP Pattern - Singleton: Enter Point

Tag: oop, pattern, singleton   Category: PHP Classes
post: 19 Feb 2008 read: 442


PHP Singleton Pattern Step By Step Tutorial - Part 1: In OOP, there are one or two resouces that are created and shared for entire application. Example, database connection. We don't need create a object every need connection. In this case, we use named Singleton pattern. A class based on singleton pattern properly instantiates and initializes one instance of the class and provide access to same object everytime. In this practice, we will create a singleton class that can certain method (can not access directly):

<?php
class CarSingleton {
  
  var $instance = NULL;
	  
  function CarSingleton($fromGetInstance = false){
    if(M_E != $fromGetInstance){
	  trigger_error('do not instantiate 
	    directly');
	}
  }
  
  function &washCar(){
	if(!$this->instance){
	  $this->instance = new CarSingleton(M_E);
	  return $this->instance;
	}
  }

}

// try to test
$obj = CarSingleton::washCar();
$obj2 = new CarSingleton;
?>
We use M_E as key.


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


615
posting