You are here: Re: making a class object global « PHP Programming Language « IT news, forums, messages
Re: making a class object global

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

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация