本文介绍了从静态方法访问非静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
}
}
我想做类似的事情,但我找不到一种可行的方法,该属性必须为静态...
I want to do something like that but I cant find a way that works, The property has to static...
推荐答案
您可以通过实例化新对象($self = new static;
)进行访问.示例代码:
You may access by instantiating a new object ($self = new static;
). The sample code:
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;
,但更多地通过编程,如果更改了类名,则不需要更新.
This is the same as calling$self = new Example;
but more programmatically, if the class name is ever changed it does not need updating.
这篇关于从静态方法访问非静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!