views:

49

answers:

2

i have this code:

class IC_Core {

    /**
     * Database
     * @var IC_Database
     */
    public static $db = NULL;

    /**
     * Core
     * @var IC_Core
     */
    protected static $_instance = NULL;

    private function __construct() {

    }

    public static function getInstance() {
        if ( ! is_object(self::$_instance)) {
            self::$_instance = new self();
            self::initialize(self::$_instance);
        }
        return self::$_instance;
    }

    private static function initialize(IC_Core $IC_Core) {
        self::$db = new IC_Database($IC_Core);
    }

}

but when i wanna access IC_Database with:

$IC = IC_Core::getInstance();
$IC->db->add() // it says that its not an object.

i think the problem lies in self::$db = new IC_Database($IC_Core);

but i dont know how to make it work.

could someone give me a hand=)

thanks!

+2  A: 

Seems to me initialize should be an instance method rather than a static one. Then the DB should be set using $this->db rather than self::$db.

    public static function getInstance() {
        if ( ! is_object(self::$_instance)) {
            self::$_instance = new self();
            self::$_instance->initialize();
        }
        return self::$_instance;
    }

    private function initialize() {
        $this->db = new IC_Database($this);
    }

You could even put the contents of the initialize method in the constructor—that way, you won't have to worry about calling it.

Samir Talwar
thanks it worked!
never_had_a_name
There seems to be little point in having a static `$_instance` with a non-static `$db`.
Tgr
@Tgr: the `$db` is local to the instance, but there's only one of them. It works in effectively the same way.
Samir Talwar
+1  A: 

the $db property is declared static thus you must access it with the double colon. the arrow notation is for non-static properties only.

$IC = IC_Core::getInstance();
IC_Core::$db->add();
Dormilich