obtaining instance of a singleton object with variable name

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
bg
Forum Contributor
Posts: 157
Joined: Fri Sep 12, 2003 11:01 am

obtaining instance of a singleton object with variable name

Post by bg »

The following works to instantiate a class with a variable name

Code: Select all

$class_name = 'blah';

$newclass = new $class_name();
I want to do something similar, except I want to get an instance of a singleton object. The following code, obviously, throws an error

Code: Select all

$class_name = 'blah';

$newclass = $class_name::instance();
The way I worked around this follows

Code: Select all

$load_driver = create_function('','if(!$retval = '.$driver_name.'::instance()){return false;} return $retval;');
However this is incredibly slow because its a user created function. If you know how to do this without a hack id like to hear it.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

from earlier: viewtopic.php?t=50097
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

You might want to take a look at the Registry pattern.
(#10850)
bg
Forum Contributor
Posts: 157
Joined: Fri Sep 12, 2003 11:01 am

Post by bg »

feyd wrote:from earlier: viewtopic.php?t=50097
Thank you sir.
Post Reply