1
我有一些問題存在於超類的變量中。看到以下兩個類別:無法正確訪問父變量
abstract class StaticEndpoint {
// API Arguments
protected $arguments;
// PDO Object
protected $PDO;
public function __construct($args) {
$this->arguments = $args;
try {
$this->PDO = new PDO('mysql:dbname=dbname;host=127.0.0.1','user', 'pass');
$this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->PDO->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public abstract function executeAll();
public abstract function executeList();
public abstract function executeOne();
}
class Endpoint extends StaticEndpoint {
public function __construct($args) {
parent::__construct($args);
}
public function executeAll() {
}
public function executeList() {
global $status,$response;
$stmt = parent::PDO->prepare("SELECT id,name FROM users");
$stmt->execute();
$users = $stmt->fetch(PDO::FETCH_ASSOC);
$status['code'] = 200;
$status['message'] = "Success";
$response = $users;
}
public function executeOne() {
}
}
但是,這將無法正常工作。我收到以下錯誤Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in /path/to/file/Endpoint.php on line 19
。第19行是$stmt = parent::PDO->prepare("SELECT id,name FROM users");
。我試圖將此線路交換出來並使用$stmt = $this->PDO->prepare("SELECT id,name FROM users");
,但這會導致以下錯誤Notice: Undefined property: Endpoint::$PDO in /path/to/file/Endpoint.php on line 19
。從超類訪問變量的正確方法是什麼?
它應該是'parent :: $ PDO' - 你需要'$'。但是'$ this-> PDO'是首選的,除非你在這兩個類中都有一個'$ PDO'屬性,並且需要專門繞過本地到父節點。 – Barmar 2015-04-01 23:53:51