Tonton MyTV dilengkapi intisari rancangan pada smart TV bermula RM4.99 sebulan. Selanjutnya →

Singleton class

Ahad, 11 September 2011, 9:18 pm0

This is continuation from singleton pattern post.

Here’s the abstract class for singleton pattern, and other classes that need to be singleton just need to extend this class.

class singleton {
    private static $instance;
    private function __construct() {}
    private function __clone() {}
    protected static function init($class) {
        if (!isset(self::$instance[$class]) ||
            !self::$instance[$class] instanceof $class) {
            self::$instance[$class] = new $class();
        }
        return self::$instance[$class];
    }
}

We can’t directly use self::$instance = new self(); because self will refer to this singleton class itself, not the class we extend. So, to get the extending class, the extending class need to explicitly pass the classname to parent class to init().

class app extends singleton {
    var $i = 0;
    static function o() {
        return parent::init(__CLASS__);
    }
    function run() {
        $this->i++;
        echo 'run app...';
    }
}
// to access app class and its methods & attr
app::o()->run();
echo app::o()->i;

Tulis komen: