php单例模式实现的方法是什么

lewis 2024-04-16 36次阅读

在PHP中,可以通过以下方法实现单例模式:

class Singleton {
    private static $instance;

    private function __construct() {
        // 私有构造函数,防止外部实例化
    }

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

        return self::$instance;
    }
}

使用该方法,只能通过Singleton::getInstance()方法获取单例实例,而无法通过new Singleton()实例化对象。这样可以确保在整个应用程序中只有一个实例存在。



发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。