Skip to content

Instantly share code, notes, and snippets.

@andrerom
Created November 27, 2010 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrerom/717891 to your computer and use it in GitHub Desktop.
Save andrerom/717891 to your computer and use it in GitHub Desktop.
Note: Singleton's are not a good pattern for unit testing, you should as much as possible look into passing object around in your application flow instead of relying on Singleton's. But there are cases where it might make a lot of sense nevertheless, for
<?php
/**
* File contains misc ways to archive Singleton pattern depending on PHP version
*
* Note that the Singleton pattern is hard to test: {@link http://www.phparch.com/2010/03/03/static-methods-vs-singletons-choose-neither/}
*/
/**
* Singleton in any PHP 5.x version using code duplication
*/
class One {
private static $instance = null;
static public function getInstance()
{
if ( self::$instance === null )
self::$instance = new self();
return self::$instance;
}
}
class Two {
private static $instance = null;
static public function getInstance()
{
if ( self::$instance === null )
self::$instance = new self();
return self::$instance;
}
}
One::getInstance();
var_dump( Two::getInstance() );
/**
* Singleton in PHP 5.3 using static::
* @see http://php.net/manual/en/language.oop5.late-static-bindings.php
*/
abstract class Singleton53
{
public static function getInstance()
{
if ( static::$instance === null )
static::$instance = new static();
return static::$instance;
}
}
class One53 extends Singleton53 {
protected static $instance = null;
}
class Two53 extends Singleton53 {
protected static $instance = null;
}
One53::getInstance();
var_dump( Two53::getInstance() );
/**
* Singleton in PHP 5.4 using Traits
*
* Traits are copied to a class and does not work like regular OOP inheritance
* @see http://simas.posterous.com/new-to-php-54-traits
*/
trait Singleton54 {
private static $instance = null;
public static function getInstance()
{
if ( self::$instance === null )
self::$instance = new self();
return self::$instance;
}
}
class One54 {
use Singleton54;
}
class Two54 {
use Singleton54;
}
One54::getInstance();
var_dump( Two54::getInstance() );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment