模式系列:单例

400 查看

关键点:使用一个静态变量去保存new出的类

<?php
class Preferences{
    private static $_instance = null;
    
    public static function getInstance(){
        if ( empty(self::$_instance) ){
            self::$_instance = new Preferences();
        }
        return self::$_instance;
    }

    public function setProperty($key, $val){
        $this->props[$key]=$val;
    }
    public function getProperty($key){
        return $this->props[$key];
    }
}


$pref = Preferences::getInstance();
$pref->setProperty('name','matt');
unset($pref);
$pref = Preferences::getInstance();
echo $pref->getProperty('name');