php单例模式,最简单的,便于理解

以下是一个最简单的单例类,留存以便参考

class TestInstance{
    static $instance;
    private $color;
    
    private function __construct(){
        $this->color = 'red';
    }
    private function __clone(){}
    
    static function getInstance(){
        if(!(self::$instance instanceof self)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function test(){
        echo $this->color.' test';
    }
}

$test = TestInstance::getInstance();

$test->test();
View Code

 

注:如果一个类的需求是用不到构造函数,那么就没有必要使用单例,静态类就完全可以解决问题

class TestStatic{
    private function __construct(){}
    
    public static function sta(){
        echo '这是个静态方法';
    }
}
TestStatic::sta();

 

posted on 2013-07-07 10:42  zper  阅读(237)  评论(0编辑  收藏  举报

导航