note 86231 modified in function.get-called-class by danbrown
| From: | danbrown@php.net | 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. <?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 ?>
--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