<?php
/**
*single pattern
*@auth webtechnic@qq.com
*/
class SinglePattern{
//保存单一实例
private static $instance;
//属性
private $val;
//getter and setter 方法
public function setVal($val){
$this->val = $val;
}
public function getVal(){
return $this->val;
}
//受保护的构造方法,不允许通过new创建类实例
private function __construct(){
}
//唯一取得类实例的方法
public static function getInstance(){
if(!self::$instance){
self::$instance = new SinglePattern();
}
return self::$instance;
}
//
public function __toString(){
return $this->val;
}
}
//测试
$test = SinglePattern::getInstance();
$test->setVal("23");
echo "{$test}<br>";
$test2 = SinglePattern::getInstance();
echo "{$test2}<br>";
?>
php 单例模式实例
最新推荐文章于 2021-03-26 18:34:48 发布