note 90360 added to language.oop5.patterns
| From: | marshall dot mattingly at NOSPAM dot gmail dot com | Date: | Fri, 17 Apr 2009 16:56:45 +0000 |
| Subject: | note 90360 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153449@lists.php.net to get a copy of this message | ||
Here's my singleton class for php 5.3.0:
<?php
class Singleton {
// this must be in every inherited singleton!
protected static $_instance;
// get the instance
final public static function instance() {
// create the instance if we don't have one
if (empty(static::$_instance)) {
$class = get_called_class(); // php 5.3.0
static::$_instance = new $class;
}
return static::$_instance;
}
// must protect the constructor
protected function __construct() { }
// overload __clone
final public function __clone() {
throw new Exception('Cannot duplicate a singleton.');
}
}
// a sample extension
class Extension extends Singleton {
// has to be here, sadly... if only statics were inherited
protected static $_instance;
protected function __construct() { ... }
public function foo() {
echo 'foo\n';
}
}
// example
$extension = Extension::instance();
$extension->foo(); // echo's 'foo\n' as expected
?>
Having to add "protected static $_instance" to every singleton is somewhat annoying. I
tried the obvious alternative and stored all the instances within an array in the Singleton class. I
ran Extension::getInstance() 1,000,000 over 10 runs to see which method was faster:
Array of $_instances: 3.47s average
Individual $_instance: 1.75s average
Considering the array of instances only had 1 key to search through, it's reasonable to assume
that method would get slower as singletons are added, whereas the method above will always stay the
same speed. The difference was enough for me to suffer the minor inconvenience.
----
Server IP: 209.41.74.194
Probable Submitter: 208.107.102.174
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- https://master.php.net/note/edit/90360
Del: integrated -- https://master.php.net/note/delete/90360/integrated
Del: useless -- https://master.php.net/note/delete/90360/useless
Del: bad code -- https://master.php.net/note/delete/90360/bad+code
Del: spam -- https://master.php.net/note/delete/90360/spam
Del: non-english -- https://master.php.net/note/delete/90360/non-english
Del: in docs -- https://master.php.net/note/delete/90360/in+docs
Del: other reasons-- https://master.php.net/note/delete/90360
Reject -- https://master.php.net/note/reject/90360
Search -- https://master.php.net/manage/user-notes.php