本文介绍了(PHP)Singleton Database类-静态方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基本网站.根据此处的答案,我正在这样做:

It's a basic website. Based off answers on here, I'm doing this:

private $db;

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

但是,如果有一个静态方法,则不能使用对象特定的变量.

But if there is a static method, I can't use the object specific variable.

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

Is there anything better than having to manually specify the db variable inside the static method?

public static function someFunction($theID){
    $db = Db::getInstance();

将变量设为静态不能解决问题.访问未声明的静态属性.我仍然必须在静态函数中分配变量.问题是问是否有办法解决这个问题.

Making the variable static doesn't solve the problem. Access to undeclared static property. I'd still have to assign the variable within the static function. The question is asking if there's a way around this.

我的数据库类(尽管对本次讨论不重要):

My DB Class (although not important to this discussion):

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;
}

}

推荐答案

是的,您可以将 $ db 设为静态:

Yes, you can make the $db static:

static private $db;

我假设这就是您所需要的,因为您是从 static 方法访问它的.如果出于某种原因您不希望这样做,则必须表示该方法可能不应该是 static .

I'm assuming that's what you need, since you're accessing it from a static method. If there's any reason why you wouldn't want this, that must mean that the method probably shouldn't be static.

根据@zerkms(感谢)注释,您可以使用 self :: :

As per @zerkms (thanks) comments, you access static variables with self:::

self::$db = Db::getInstance();

这篇关于(PHP)Singleton Database类-静态方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:24