在了解设计模式的同时,我遇到了单例模式:
class Singleton
{
private static $instance = null;
private function __construct()
{
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
我很难理解构造函数在这种情况下的作用.大括号之间没有执行任何代码?这是如何运作的?谢谢.
解决方法:
标记为private的构造函数用于避免单例类的实例化,因此始终只有一个.
例如,我们不能这样做:
$singleton = new Singleton();
它产生:
Fatal error: Call to private Singleton::__construct() from invalid context
你必须获取单身人士:
$singleton = Singleton::getInstance();
标签:php,singleton
来源: https://codeday.me/bug/20190823/1698949.html