在一些开源代码上,他们为什么使用:
$router = Cfw_Router::getInstance();
不仅仅是使用
$rounter = new Cfw_Router();
有什么优势吗?
getInstance()
:
public static function getInstance() {
if (null === self::$__instance) {
self::$__instance = new self();
}
return self::$__instance;
}
最佳答案
他们正在使用 singleton pattern .基本上,它只允许在任何给定时间存在一个实例。但是,它有时可用于提供全局变量,这在设计中并不总是最好的(请参阅上面链接中的批评)。
关于php - 新关键字与创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10199228/