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.