无法访问子类中的pdo连接

时间:2014-12-26 17:27:44

标签: 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 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?
    }
}

这个问题的症结我不想访问子类中构造函数中创建的父连接,非常感谢指南。

1 个答案:

答案 0 :(得分:0)

由于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->.....

    }
}