使用单例方法来创建一个全局对象
问题描述:
我想使用单例方法来访问一个全局对象(在这个例子中它的“用户名”)。我的问题是如何修改这个,以便在DB->connect()
函数中我可以做echo $this->username;
而不是声明$ username或更改最后2行?使用单例方法来创建一个全局对象
class CI_Base {
private static $instance;
public function CI_Base()
{
self::$instance =& $this;
}
public static function &get_instance()
{
return self::$instance;
}
}
function &get_instance() {
return CI_Base::get_instance();
}
class Foo {
function run() {
$CI = & get_instance();
$CI->username = "test";
$db = new DB;
$db->connect();
}
}
class DB extends Foo {
function connect() {
$CI = & get_instance();
echo $CI->username;
}
}
$foo = new Foo;
$foo->run();
答
这应该工作
class Foo {
function __get($field) {
if ($field == "username") {
//don't need to create get_instance function
$CI = CI_Base::get_instance();
return $CI->username;
}
}
}
你可以通过所有访问来自富不存在的领域,达到实例对象:
class Foo {
function __get($field) {
$CI = CI_Base::get_instance();
return $CI->$field;
}
}
class DB extends Foo {
function connect() {
// this->username will call __get magic function from base class
echo this->username;
}
}
在PHP5你不需要在get_instance
之前加上&符号,因为所有对象都通过引用传递。
+1
没有冒犯,OP要求这样做,但我为那个必须维护,测试和调试这个噩梦的可怜家伙感到可惜。 – Gordon 2010-10-05 15:46:46
Singleton是[pattern](http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29),而不是一种方法。 [你应该避免它](http://stackoverflow.com/questions/1996230/how-bad-are-singletons)。 – Gordon 2010-10-05 14:17:11