Voting

: four minus zero?
(Example: nine)

The Note You're Voting On

danbettles at yahoo dot co dot uk
16 years ago
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function. When called in a static method, this function returns the name of the class the call was made against.

<?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

<< Back to user notes page

To Top