简体   繁体   English

无法访问子类中的pdo连接

[英]can't access pdo connection in child class

I am having a problem making a pdo connection accessible over extended classes eg : 我在通过扩展类访问pdo连接时遇到问题,例如:

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
        );
    }
}

And another class extending model 还有另一个类扩展模型

class User extends Model { 
    public function someFunction(){
        // how can I access the pdo connection in the parent constructer here?
    }
}

Thats the crux of the issue I wan't to access the parent connection created in the constructor in child classes, guidance much appreciated. 这就是问题的症结所在,我无法访问子类中在构造函数中创建的父连接,对此指南非常感谢。

As constructors are not implicitly called in PHP, you need to add some lines at least, and afterwards just use $this : 由于在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->.....

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM