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

Posted by Jerry Stuckle on 11/17/06 12:30

Michael Fesser wrote:
> .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

Micha,

Yes, this works great. I've been using similar code in C++ since the 80's.

Using the class name or self is a matter of programming style. I prefer
the class name - I find it to be easier for new programmers to understand.

And that's the same reason I don't use buzzwords such as "singleton"
when describing how code works. I prefer a clear explanation in simple
English, especially here where for many readers English isn't a first
language.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

 

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

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