Page 1 of 1
Variable(s) accessible to all objects
Posted: Mon Sep 26, 2005 9:16 am
by Ree
I have an array of strings, which I want all of my objects to be able to use. One way to do that would be putting
in all of the methods that need to use it in all of the classes that have such methods. Another - passing the array itself to methods. Both ways look awful to me. Is there a nice and painless way to achieve the functionality I need?
Posted: Mon Sep 26, 2005 9:31 am
by feyd
you could grab them from the superglobals, but it's advised you pass the information in some fashion. Alternately, a singleton could work as well.. which is basically the same but the data is stored in an object instead.
Posted: Mon Sep 26, 2005 9:40 am
by Ree
Is it worth writing a class just for storing the array? Not sure, but I'll try that singleton thing.
Posted: Mon Sep 26, 2005 11:16 am
by Ree
Have a look at this:
Code: Select all
class LanguageData
{
function LanguageData()
{
}
function getString($key)
{
include('en.php');
return $lang[$key];
}
}
class UserClass
{
function UserClass()
{
}
function needsLanguageInfo()
{
//code
$string = LanguageData::getString(256);
}
}
Why would I want to use singleton if I can simply access the language string I need via class::method()? It seems to solve my problem, but maybe singleton has advantages I'm not aware of?
Posted: Mon Sep 26, 2005 11:39 am
by feyd
your code will on each call load the file via the include. You may only want to load it once.
Posted: Mon Sep 26, 2005 3:16 pm
by Ree
Now does that look like a possible singleton usage? It's just an example, of course.
Code: Select all
define('LANG', 'en.php');
class LanguageData
{
var $lang;
function LanguageData($file)
{
include($file);
}
function &Singleton($file)
{
static $object;
if (!isset($object))
{
$object = new LanguageData($file);
}
return $object;
}
function getString($type, $number)
{
return $this->lang[$type][$number];
}
}
class Test
{
var $lang;
function Test()
{
$this->lang = &LanguageData::Singleton(LANG);
}
function needsSomeString()
{
$string = $this->lang->getString('type', 5);
//do stuff
}
}
Posted: Mon Sep 26, 2005 3:18 pm
by feyd
yes, that's a singleton roughly.. for php4 anyways

Posted: Mon Sep 26, 2005 3:50 pm
by Ree
roughly... that means incorrect in some ways? and yes, I use php4.
Posted: Mon Sep 26, 2005 3:53 pm
by feyd
no, perfectly fine for php4.
Posted: Mon Sep 26, 2005 7:35 pm
by Ambush Commander
Basically, it's a slightly wizard-ish trick that doesn't bend any rules and is portable to php5 but don't use it too often or you may confuse people.