2014-12-26 44 views
0

我有一个问题作出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? 
    } 
} 

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

+3

这是错误的创建模型对象的连接,反正访问父母的财产,你可以简单地使用'$ this-> connection ...'在子节点 –

+2

由于'User extends Model',你可以访问'$ this-> connection'。 –

回答

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

    } 
} 
+0

如果我不喜欢这个 静态函数someFunction(){服用点// 访问父这里PDO连接: 的var_dump($这个 - >连接) } 它返回一个错误 使用$此当不在对象上下文中 –

+0

这是因为我的函数someFunction被声明为static –