note 95196 added to language.oop5.patterns
| From: | quentinberlemont at gmail dot com | Date: | Thu, 17 Dec 2009 17:01:41 +0000 |
| Subject: | note 95196 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-164094@lists.php.net to get a copy of this message | ||
<?php
/**
* Class Singleton is a generic implementation of the singleton design pattern.
*
* Extending this class allows to make a single instance easily accessible by
* many other objects.
*
* @author Quentin Berlemont <quentinberlemont@gmail.com>
*/
abstract class Singleton
{
/**
* Prevents direct creation of object.
*
* @param void
* @return void
*/
protected function __construct() {}
/**
* Prevents to clone the instance.
*
* @param void
* @return void
*/
final private function __clone() {}
/**
* Gets a single instance of the class the static method is called in.
*
* See the {@link http://php.net/lsb Late Static Bindings}
feature for more
* information.
*
* @param void
* @return object Returns a single instance of the class.
*/
final static public function getInstance()
{
static $instance = null;
return $instance ?: $instance = new static;
}
}
?>
E.g.
<?php
// Foo class
class Foo extends \Framework\Core\Singleton
{
// Bar method
public function bar()
{
echo __CLASS__ . PHP_EOL;
}
}
// Returns a single instance of Foo class
$foo = Foo::getInstance();
// Prints: Foo
$foo->bar();
?>
Best regards,
Quentin.
----
Server IP: 195.221.21.36
Probable Submitter: 84.103.144.176
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- https://master.php.net/note/edit/95196
Del: integrated -- https://master.php.net/note/delete/95196/integrated
Del: useless -- https://master.php.net/note/delete/95196/useless
Del: bad code -- https://master.php.net/note/delete/95196/bad+code
Del: spam -- https://master.php.net/note/delete/95196/spam
Del: non-english -- https://master.php.net/note/delete/95196/non-english
Del: in docs -- https://master.php.net/note/delete/95196/in+docs
Del: other reasons-- https://master.php.net/note/delete/95196
Reject -- https://master.php.net/note/reject/95196
Search -- https://master.php.net/manage/user-notes.php