Posted by Michael Fesser on 11/17/06 10:32
..oO(Jerry Stuckle)
>Ok, there's another way have a static method to return it, i.e.
> (PHP5 - and not tested so may contain some syntax errors)
>
>class Test {
> private static $me = null;
>
> public static function getTest() {
> if (Test::$me == null)
> Test::$me = new Test;
> return Test::$me;
> }
>}
Should work, even if I would call it getInstance() to be more generic.
You could also use the keyword 'self' instead of the class name inside
the function:
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
Then if you should need this function in another class you just have to
copy it. But that's more or less just personal preference. It works the
same.
>Test::$me is a private static variable which is shared amongst all
>instances.
JFTR: There's always only _one_ instance. That's why this is called a
singleton.
Micha
[Back to original message]
|