views:

50

answers:

1

I am trying to use the singleton method to access a global object (in this example its "username"). My question is how can I modify this so that in the DB->connect() function I could do echo $this->username; without declaring $username or changing the last 2 lines?

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();
A: 

This should work

class Foo {
  function __get($field) {
    if ($field == "username") {
        //don't need to create get_instance function
        $CI = CI_Base::get_instance(); 
        return $CI->username;
    }
  }
}

you can pass all access to non existing fields from Foo to $instance object:

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;
    }
}

in php5 you don't need to put ampersand before get_instance becouse all objects are passed by reference.

jcubic
No offense, the OP asked for it, but I feel pity for the poor fellow who has to maintain, test and debug this nightmare.
Gordon