note 111141 added to language.oop5.late-static-bindings
| From: | VladSun | Date: | Fri, 18 Jan 2013 21:59:02 +0000 |
| Subject: | note 111141 added to language.oop5.late-static-bindings | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-193209@lists.php.net to get a copy of this message | ||
The Singleton pattern base class:
<?php
/**
*
* Singleton pattern base class.
*
* @author VladSun
* @license GPL v2.0
* @version 0.1b
*/
abstract class Singleton {
private static $instance;
/**
* __construct
* Constructor can't be called directly, thus getInstance()
* is the only way to instantinate the class
*
* @access private
*/
private function __construct() {
}
/**
* __clone
* Singletons can't be cloned
*
* @final
* @access public
* @throws BadMethodCallException
*/
public final function __clone() {
throw new BadMethodCallException('Clone is not allowed.');
}
/**
* __wakeup
* Singletons can't be deserialized
*
* @final
* @access public
* @throws BadMethodCallException
*/
public final function __wakeup() {
throw new BadMethodCallException('Deserializing is not allowed.');
}
/**
* getInstance
* Return the one and only instance of the class
*
*
* @static
* @final
* @access public
* @return Singleton Singleton instance
*/
public static final function getInstance() {
if (!self::$instance) {
self::$instance = new static;
}
return self::$instance;
}
}
?>
<?php
class A_Class extends Singleton {
public function echoMyClass() {
echo get_class($this);
}
}
$a = A_Class::getInstance();
$a->echoMyClass();
?>
Output:
A_Class
----
Server IP: 69.147.83.199
Probable Submitter: 212.117.50.108
----
Manual Page -- http://php.net/manual/en/language.oop5.late-static-bindings.php
Edit -- https://master.php.net/note/edit/111141
Del: integrated -- https://master.php.net/note/delete/111141/integrated
Del: useless -- https://master.php.net/note/delete/111141/useless
Del: bad code -- https://master.php.net/note/delete/111141/bad+code
Del: spam -- https://master.php.net/note/delete/111141/spam
Del: non-english -- https://master.php.net/note/delete/111141/non-english
Del: in docs -- https://master.php.net/note/delete/111141/in+docs
Del: other reasons-- https://master.php.net/note/delete/111141
Reject -- https://master.php.net/note/reject/111141
Search -- https://master.php.net/manage/user-notes.php