关键点:使用一个静态变量去保存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');

甄城
1.2k 声望34 粉丝