Php can';t访问子类中的pdo连接
我在通过扩展类访问pdo连接时遇到问题,例如:Php can';t访问子类中的pdo连接,php,pdo,Php,Pdo,我在通过扩展类访问pdo连接时遇到问题,例如: class Model { public $connection; public function __construct(PDO $connection = null) { global $config; $this->connection = $connection; if ($this->connection === null) { $this->connection = new
class Model {
public $connection;
public function __construct(PDO $connection = null)
{
global $config;
$this->connection = $connection;
if ($this->connection === null) {
$this->connection = new PDO(
'mysql:host='.$config['db_host'].';dbname='.$config['db_name'], $config['db_username'], $config['db_password']);
$this->connection->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
}
}
和另一个类扩展模型
class User extends Model {
public function someFunction(){
// how can I access the pdo connection in the parent constructer here?
}
}
这是我不想访问子类中构造函数中创建的父连接的问题的症结所在,非常感谢您的指导。由于在PHP中构造函数不是隐式调用的,您至少需要添加一些行,然后只需使用
$this
:
class User extends Model {
public function __construct(PDO $connection = null) {
parent::__construct($connection);
}
public function someFunction(){
// access the pdo connection in the parent here:
$this->connection->.....
}
}
在模型对象中创建连接是错误的,无论如何,要访问父对象的属性,您可以在child中简单地使用
$this->connection…
,因为用户扩展了模型
,所以您只需访问$this->connection
。如果我执行类似于此静态函数someFunction()的操作{//access the parent here:var_dump($this->connection)}当不在对象上下文中时,它使用$this返回一个错误,这是因为我的函数someFunction被声明为static