Return to Snippet

Revision: 82324
at July 27, 2020 14:10 by koncept


Updated URL


Updated Code
<?php
declare(strict_types=1);

/**
 * Singleton design pattern implementation
 */
class Singleton {

  /** @var object[]  */
  private static $instances = [];

  private function __construct() {
  }

  /**
   * @param string $class The class name to invoke
   *
   * @return mixed
   */
  public static function getInstance(string $class) {
    if (!array_key_exists($class, self::$instances)) {
      self::$instances[$class] = new $class();
    }
    return self::$instances[$class];
  }
}

// Usage - provide a class name to getInstance to invoke it
$instance = Singleton::getInstance(Singleton::class);

Updated Description
A Singleton design pattern in PHP.

Revision: 2207
at April 1, 2010 23:02 by koncept


Updated Code
<?php 
/**
 * Singleton design pattern implementation for PHP5
 */
class Singleton
{
	private static $instances = array();

	private function __construct(){}

	public static function getInstance( $class = null )
	{
		if( is_null( $class ) )
		{
			trigger_error( "Missing class information", E_USER_ERROR );
		}
		if( !array_key_exists( $class, self::$instances ) )
		{
			self::$instances[ $class ] = new $class;
		}
		return self::$instances[ $class ];
	}
	public final function __clone()
	{
		trigger_error( "Cannot clone instance of Singleton pattern", E_USER_ERROR );
	}
}

// Usage
$instance = Singleton::getInstance( 'SomeClass' );
?>

Revision: 2206
at January 16, 2007 18:29 by koncept


Updated Code
<?php 
/**
 * Singleton design pattern implementation for PHP5
 */
class Singleton
{
	private static $instances = array();

	private function __construct(){}

	public function getInstance( $class = null )
	{
		if( is_null( $class ) )
		{
			trigger_error( "Missing class information", E_USER_ERROR );
		}
		if( !array_key_exists( $class, self::$instances ) )
		{
			self::$instances[ $class ] = new $class;
		}
		return self::$instances[ $class ];
	}
	public final function __clone()
	{
		trigger_error( "Cannot clone instance of Singleton pattern", E_USER_ERROR );
	}
}

// Usage
$instance = Singleton::getInstance( 'SomeClass' );
?>

Revision: 2205
at January 16, 2007 18:27 by koncept


Initial Code
<?php 
/**
 * Singleton design pattern implimentation for PHP5
 */
class Singleton
{
	private static $instances = array();

	private function __construct(){}

	public function getInstance( $class = null )
	{
		if( is_null( $class ) )
		{
			trigger_error( "Missing class information", E_USER_ERROR );
		}
		if( !array_key_exists( $class, self::$instances ) )
		{
			self::$instances[ $class ] = new $class;
		}
		return self::$instances[ $class ];
	}
	public final function __clone()
	{
		trigger_error( "Cannot clone instance of Singleton pattern", E_USER_ERROR );
	}
}

// Usage
$instance = Singleton::getInstance( 'SomeClass' );
?>

Initial URL


Initial Description


Initial Title
PHP5 Singleton Design Pattern

Initial Tags
php

Initial Language
PHP