filts 发表于 2017-3-20 11:44:52

php 单例模式

  今天学到单例模式,在网上找了点资料。结合资料做的测试!
  singer.php

class singer
{
static private $instance = null;                        //静态变量$instance
private $state = 0;
public static function getInstance()
{
if(self::$instance == null)
{
self::$instance = new singer();//self : 是对类本身的一个引用
}
return self::$instance;
}
private function singer(){}//构造方法
private function __clone(){}      //防止对象被复制或克隆   clone()-> 复制对象在public时 可以复制对象
function setSinger($state)//给$switch 赋值的方法
{
$this->state = $state;
}
function getSinger()          //取得$switch 值的方法
{
return $this->state;
}
}
  singer.php

singer::getInstance()->setSinger(1);
$state = singer::getInstance()->getSinger()== 0 ? '已关闭' : '已开启';
echo '状态:'.$state;
   只是拥有以下3种公共元素:


    1.
必须要有私有的构造函数                                --> singer()

    2.
拥有一个保存类实例的静态变量                       --> $instance

    3.
拥有可以访问这个实例的公共静态方法              --> getInstance()
页: [1]
查看完整版本: php 单例模式