栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

php单例模式

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

php单例模式

    单例即一个类是能有一个实例,并提供一个当前类的全局唯一访问入口(getInstance)。防止类被多次实例化和clone。

一、单例模式
test();

// new Singleton(); // Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context
// clone $single1; // Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context

    输出:

object(Singleton)#1 (0) { } object(Singleton)#1 (0) { } 这是一个单例模式
二、单例模式的应用
tp6框架容器中单例模式:
class Container implements ContainerInterface, ArrayAccess, IteratorAggregate, Countable
{
    
    protected static $instance;

    
    protected $instances = [];

    
    protected $bind = [];

    
    protected $invokeCallback = [];

    
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }

        if (static::$instance instanceof Closure) {
            return (static::$instance)();
        }

        return static::$instance;
    }
    
    // ...
    
}
数据库连接
query('set names utf8mb4');
            self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die('error:' . $e->getMessage());
        }
    }

    // 禁止clone
    private function __clone()
    {

    }

    public static function getInstance(): object
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function query(string $sql = ''): array
    {
        return self::$db->query($sql)->fetch();
    }

}

$mysql = SingletonMysql::getInstance();

var_dump($mysql->query('SELECT VERSION();'));

  输出结果:

array(2) { ["VERSION()"]=> string(6) "5.7.26" [0]=> string(6) "5.7.26" }

测试代码下载:

singleton.zip

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/2463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号