note 93677 modified in language.oop5.patterns by danbrown
| From: | danbrown@php.net | Date: | Tue, 22 Sep 2009 18:48:27 +0000 |
| Subject: | note 93677 modified in language.oop5.patterns by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-160946@lists.php.net to get a copy of this message | ||
The Singleton class version wich is useable by only extending it :
you would use is for example like this :
<?php
class Users extends Singleton
{
// ...
public function SomeMethod()
{
}
}
?>
and in your code :
<?php
Users::inst()->SomeMethod();
?>
I didn't check for performance, but here is the code :
<?php
class Singleton
{
// Hold an instance of the class
private static $instances = array();
// A private constructor; prevents direct creation of object
final private function __construct()
{
}
// Prevent users to clone the instance
final public function __clone()
{
trigger_error( 'Clone is not allowed.', E_USER_ERROR );
}
// The singleton method
final public static function inst()
{
$c = get_called_class();
if( ! isset( self::$instances[$c] ) )
{
self::$instances[$c] = new $c;
}
return self::$instances[$c];
}
}
?>
--was--
The Singleton class version wich is useable by only extending it :
you would use is for example like this :
class Users extends Singleton
{
...
public function SomeMethod()
{
}
}
and in your code :
...
Users::inst()->SomeMethod();
...
I didn't check for performance, but here is the code :
class Singleton
{
// Hold an instance of the class
private static $instances = array();
// A private constructor; prevents direct creation of object
final private function __construct()
{
}
// Prevent users to clone the instance
final public function __clone()
{
trigger_error( 'Clone is not allowed.', E_USER_ERROR );
}
// The singleton method
final public static function inst()
{
$c = get_called_class();
if( ! isset( self::$instances[$c] ) )
{
self::$instances[$c] = new $c;
}
return self::$instances[$c];
}
}
http://php.net/manual/en/language.oop5.patterns.php