我在从超类访问变量时遇到了一些问题。请参阅以下两个类:
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
。从超类访问变量的正确方法是什么?
答案 0 :(得分:2)
$this->PDO
是访问父类的公共/受保护字段的正确语法。该错误消息告诉我,当您收到错误时,可能没有Endpoint正确扩展StaticEndpoint。