php单例模式

ThinkPhp 发表时间:2020-03-14 17:04:18 作者:梁子亮 浏览次数:822

在common/controller下新建Single.php文件

<?php
namespace app\common\controller;
use think\Controller;
use think\Db;

class Single extends Controller
{

    private static $_instance;
    private $name;

    protected function __construct(){
        parent::__construct();
    }

    protected function __clone(){

    }

    public static function getInstance(){
        if (empty(self::$_instance)) {
            self::$_instance = new Single();
        }
        return self::$_instance;
    }
    
    public function set($re){
        $this->name = $re;

    }

    public function get(){

        return $this->name;

    }
}

在index/controller/Index.php下使用(若在相同的模块下(app/common/)则无需使用以下use即可直接使用)

use app\common\controller\Single;
$a = Single::getInstance();
$b = Single::getInstance();
$a->set(123);
$b->set(333);
$c = $a->get();
$d = $b->get();
print_dump($c,$d);die;

结果为:

int(333)
int(333)