0

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();
Galen
  • 29,976
  • 9
  • 71
  • 89
fire
  • 21,383
  • 17
  • 79
  • 114
  • 3
    Singleton is a [pattern](http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29), not a method. [And you should avoid it](http://stackoverflow.com/questions/1996230/how-bad-are-singletons). – Gordon Oct 05 '10 at 14:17

1 Answers1

1

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
  • 61,973
  • 54
  • 229
  • 402
  • 1
    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 Oct 05 '10 at 15:46