我创建了这个父类
class DBMysqli {
private $mysqli;
function __construct($Mysqli) {
$this->mysqli = $Mysqli;
}
public function GET($queryArr){
$query = "SELECT ";
...
$result = $this->mysqli->query($query); //Here I get a run time error!!
echo $this->mysqli->error;
return $result;
}
}
和儿童班
class FolderComment extends DBMysqli{
protected $data;
public function __construct() {
$this->mysqli = DB::Simulator(); //works, initiliaze $mysqli
$table = array(
'tables' => 'folder_comments',
'conditions' => '1'
);
$this->data = $this->GET($table);
}
}
我收到运行时错误,指出 $this->mysqli 为空。 但我已在子类中设置了它。我想这是一个 OOP 轻描淡写的问题。
更改
private $mysqli;
自
protected $mysqli;
在普伦特类中
,既然你已经把mysqli变成了一个私有变量,它就不会像你假设的那样在孩子的构造函数中设置。如果您希望儿童能够访问它,则应对其进行保护。
因此,正在发生的事情是您在子类中创建一个名为 mysqli
的新变量,因为它从一开始就从未从父类继承私有字段。
另一种选择是隐式调用父级的构造函数,并向其发送mysqli
变量。
你需要将 mysqli 对象传递给你的父类
public function __construct() {
parent::__construct(DB::Simulator());
$table = array(
'tables' => 'folder_comments',
'conditions' => '1'
);
$this->data = $this->GET($table);
}
在DBMysqli
中,你需要$mysqli
protected
,而不是private
class DBMysqli {
protected $mysqli;
//...
Private 表示阻止任何访问(外部或继承),而受保护表示阻止外部访问,但继承的对象可以访问该属性。