(PHP)Singleton数据库类 - 静态方法怎么样?

Mar*_*cus 3 php database variables singleton static

这是一个基本的网站.根据这里的答案,我这样做:

private $db;

public function __construct($id = null) {
    $this->db = Db::getInstance(); //singleton from the Db class
Run Code Online (Sandbox Code Playgroud)

但是如果有静态方法,我就不能使用特定于对象的变量.

有没有什么比在静态方法中手动指定db变量更好的了?

public static function someFunction($theID){
    $db = Db::getInstance();
Run Code Online (Sandbox Code Playgroud)

编辑:使变量静态不能解决问题.Access to undeclared static property.我仍然需要在静态函数中分配变量.问题是询问是否有解决方法.

我的数据库类(虽然对此讨论不重要):

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;
}
Run Code Online (Sandbox Code Playgroud)

}

Luc*_*ore 5

是的,你可以制作$db静态:

static private $db;
Run Code Online (Sandbox Code Playgroud)

我假设这是你需要的,因为你是从一个static方法访问它.如果有任何理由你不想要这个,那必然意味着该方法可能不应该static.

编辑:

根据@zerkms(谢谢)注释,您可以访问静态变量self:::

self::$db = Db::getInstance(); 
Run Code Online (Sandbox Code Playgroud)