note 86231 modified in function.get-called-class by danbrown

From: Date: Fri, 08 Jun 2012 20:19:15 +0000
Subject: note 86231 modified in function.get-called-class by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-188498@lists.php.net to get a copy of this message
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class.&#13;&#10;&#13;&#10;&#60;?php&#13;&#10;&#13;&#10;abstract class Singleton {&#13;&#10;&#13;&#10; protected function __construct() {&#13;&#10; }&#13;&#10;&#13;&#10; final public static function getInstance() {&#13;&#10; static $aoInstance = array();&#13;&#10;&#13;&#10; $calledClassName = get_called_class();&#13;&#10;&#13;&#10; if (! isset ($aoInstance[$calledClassName])) {&#13;&#10; $aoInstance[$calledClassName] = new $calledClassName();&#13;&#10; }&#13;&#10;&#13;&#10; return $aoInstance[$calledClassName];&#13;&#10; }&#13;&#10;&#13;&#10; final private function __clone() {&#13;&#10; }&#13;&#10;}&#13;&#10;&#13;&#10;class DatabaseConnection extends Singleton {&#13;&#10;&#13;&#10; protected $connection;&#13;&#10;&#13;&#10; protected function __construct() {&#13;&#10; // @todo Connect to the database&#13;&#10; }&#13;&#10;&#13;&#10; public function __destruct() {&#13;&#10; // @todo Drop the connection to the database&#13;&#10; }&#13;&#10;}&#13;&#10;&#13;&#10;$oDbConn = new DatabaseConnection(); // Fatal error&#13;&#10;&#13;&#10;$oDbConn = DatabaseConnection::getInstance(); // Returns single instance&#13;&#10;?&#62; --was-- It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class. <?php abstract class Singleton { protected function __construct() { } final public static function getInstance() { static $aoInstance = array(); $calledClassName = get_called_class(); if (! isset ($aoInstance[$calledClassName])) { $aoInstance[$calledClassName] = new $calledClassName(); } return $aoInstance[$calledClassName]; } final private function __clone() { } } class DatabaseConnection extends Singleton { protected $connection; protected function __construct() { // @todo Connect to the database } public function __destruct() { // @todo Drop the connection to the database } } $oDbConn = new DatabaseConnection(); // Fatal error $oDbConn = DatabaseConnection::getInstance(); // Returns single instance ?> Full write-up in Oct 2008: http://danbettles.blogspot.com http://php.net/manual/en/function.get-called-class.php

« previous php.notes (#188498) next »