note 82985 added to language.oop5.patterns
| From: | someone at somewhere dot com | Date: | Mon, 05 May 2008 08:20:56 +0000 |
| Subject: | note 82985 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-139068@lists.php.net to get a copy of this message | ||
If you want a singleton and you don't mind on throwing a stop error/exception when a 2nd
instace is created instead of returning the already created object, then this code works with
subclassing and without getInstace alike functions (just with __construct)
<?php
class SINGLETON
{
// the array for checking the created instances
protected static $singletons = array ();
// make it final so extended classes cannot override it
final public function __construct ()
{
$classname = get_class ( $this );
if ( ! isset ( self::$singletons[$classname] ) )
// instead of $this it could be any value since we are checking for isset, but a
reference to the object may be useful in a possible improvement, somewhat
self::$singletons[$classname] = $this;
else
// your favorite stop error here
trow new Exception ();
}
// final as well, no overriding, plus protected so it cannot be called
final protected function __clone () {}
}
class X extends SINGLETON
{
//...
}
class Y extends X
{
//...
}
$x = new X ();
$y = new Y ();
$a = new X (); // execution stops, as an instance of X is created already
$b = new Y (); // execution stops, as an instance of Y is created already, it DOES NOT give problems
with X, despite extending X
?>
so, if it is ok to stops the execution, this method is way simpler
it must stops the execution because no matter what, __construct will return a reference to the new
object, always, so if the script goes on further you will have effectively 2 instances (as a matter
of fact, the code above only checks the existence of another object from the same class, it does not
prohibit the creation of a new one)
hth
----
Server IP: 209.41.74.194
Probable Submitter: 213.60.58.100
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- https://master.php.net/note/edit/82985
Del: integrated -- https://master.php.net/note/delete/82985/integrated
Del: useless -- https://master.php.net/note/delete/82985/useless
Del: bad code -- https://master.php.net/note/delete/82985/bad+code
Del: spam -- https://master.php.net/note/delete/82985/spam
Del: non-english -- https://master.php.net/note/delete/82985/non-english
Del: in docs -- https://master.php.net/note/delete/82985/in+docs
Del: other reasons-- https://master.php.net/note/delete/82985
Reject -- https://master.php.net/note/reject/82985
Search -- https://master.php.net/manage/user-notes.php