从静态方法访问非静态属性

2022-08-30 23:01:44
class database{
    protected $db;

    protected function connect(){
        $this->db = new mysqli( /* DB info */ ); // Connecting to a database
    }
}

class example extends database{
    public function __construct(){
        $this->connect();
    }

    public static function doQuery(){
        $query = $this->db->query("theQuery");   // Not working.
        $query = self::$db->query("theQuery");   // Not working.
        $query = parent::$db->query("theQuery"); // Also not working.
    }
}

我想做这样的事情,但我找不到一种可行的方法,财产必须静态...


答案 1

您可以通过实例化新对象 () 进行访问。示例代码:$self = new static;

class Database{

    protected $db;

    protected function connect(){
        $this->db = new mysqli( /* DB info */ ); // Connecting to a database
    }
}


class Example extends Database{

    public function __construct(){
        $this->connect();
    }

    public static function doQuery(){

        $self = new static; //OBJECT INSTANTIATION
        $query = $self->db->query("theQuery");   // working.

    }
}

这与调用相同,但更以编程方式进行,如果类名发生更改,则不需要更新。$self = new Example;


答案 2

不能从静态方法访问非静态属性。非静态属性仅属于实例化对象,其中每个实例化对象都有一个单独的属性值。

我将举一个例子来说明,这段代码不起作用

class Example {
    public $a;

    public function __construct($a) {
        $this->a = $a;
    }
    public static function getA() {
        return $this->a;
    }
}

$first = new Example(3);
$second = new Example(4);

// is $value equal to 3 or 4?
$value = Example::getA();

推荐