【发布时间】:2011-12-28 00:15:11
【问题描述】:
这是一个基本的网站。根据此处的答案,我正在这样做:
private $db;
public function __construct($id = null) {
$this->db = Db::getInstance(); //singleton from the Db class
但是如果有静态方法,我就不能使用对象特定的变量了。
有什么比在静态方法中手动指定 db 变量更好的方法?
public static function someFunction($theID){
$db = Db::getInstance();
编辑:将变量设为静态并不能解决问题。 Access to undeclared static property。我仍然必须在静态函数中分配变量。问题是问是否有办法解决这个问题。
我的 DB 类(尽管对本次讨论并不重要):
class Db {
private static $m_pInstance;
private function __construct() { ... }
public static function getInstance(){
if (!self::$m_pInstance)
self::$m_pInstance = new Db();
return self::$m_pInstance;
}
}
【问题讨论】:
-
有什么原因不能在
someFunction中使用$this->db?为什么还要在构造函数中设置它? -
不要使用静态方法
-
@DaOgre:
someFunction是静态的 -
仅供参考:Db::getInstance() 不是单例,它是一个工厂,它返回一个单例。
-
@Digital Precision:你为什么这么认为?此外,还有 2 种不同的 工厂模式。你提到的是哪一个?
标签: php database variables static singleton