PHP 8.5.0 Alpha 1 available for testing

Voting

: min(one, nine)?
(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 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
?>

<< Back to user notes page

To Top