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

Whi*_*lue 15 php 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(){
        $query = $this->db->query("theQuery");   // Not working.
        $query = self::$db->query("theQuery");   // Not working.
        $query = parent::$db->query("theQuery"); // Also not working.
    }
}
Run Code Online (Sandbox Code Playgroud)

我想做类似的事情,但我找不到有效的方法,该属性必须静态......

Mah*_*bub 19

您可以通过实例化新对象($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.

    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*o D 8

您无法从静态方法访问非静态属性.非静态属性仅属于实例化对象,其中每个实例化对象都具有单独的属性值.

我将举例说明,此代码不起作用:

class Example {
    public $a;

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

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

// is $value equal to 3 or 4?
$value = Example::getA();
Run Code Online (Sandbox Code Playgroud)