<?php
/*
*
* @Author: Zuhair Mirza
* @Implementation Of Singleton Design Pattern in PHP
* @Date : 12-June-2015
* @Defination : In software engineering, the singleton pattern is a design pattern that
* restricts the instantiation of a class to one object. This is useful when exactly one
* object is needed to coordinate actions across the system.
*/
class Singleton {
/**
* Returns the *Singleton* instance of this class.
*
* @staticvar Singleton $instance The *Singleton* instances of this class.
*
* @return Singleton The *Singleton* instance.
*/
public static function getInstance() {
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
protected function __construct() {
}
private function __clone() {
}
private function __wakeup() {
}
}
class SingletonChild extends Singleton {
}
$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance()); // Output : bool(true)
$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance()); // Output : bool(false)
var_dump($obj === Singleton::getInstance()); // Output : bool(true)
/*
*
* @Author: Zuhair Mirza
* @Implementation Of Singleton Design Pattern in PHP
* @Date : 12-June-2015
* @Defination : In software engineering, the singleton pattern is a design pattern that
* restricts the instantiation of a class to one object. This is useful when exactly one
* object is needed to coordinate actions across the system.
*/
class Singleton {
/**
* Returns the *Singleton* instance of this class.
*
* @staticvar Singleton $instance The *Singleton* instances of this class.
*
* @return Singleton The *Singleton* instance.
*/
public static function getInstance() {
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
protected function __construct() {
}
private function __clone() {
}
private function __wakeup() {
}
}
class SingletonChild extends Singleton {
}
$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance()); // Output : bool(true)
$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance()); // Output : bool(false)
var_dump($obj === Singleton::getInstance()); // Output : bool(true)
No comments:
Post a Comment