PHP:子类无法访问MySQL对象

时间:2018-10-11 17:44:09

标签: php mysql class

使用功能chief,我试图启动一个mysql连接,该连接将由多个类/函数全局使用。

当我将此类扩展到session类时,子类无法访问mysql对象$db

class chief {

    protected $db;

    public function __construct() {

        $this->db=new stdClass();

        $this->db=new mysqli('', '', '', '');
    }

}

class session extends chief {
    public function __construct($address=null) {

        var_dump($this->db);
    }
}

打印结果:

chief Object
(
    [db:protected] => mysqli Object
        (
            [affected_rows] => 0
            [client_info] => mysqlnd 5.0.12-dev - 20150407 - $Id: 38fea24f2847fa7519001be390c98ae0acafe387 $
            [client_version] => 50012
            [connect_errno] => 0
            [connect_error] => 
            [errno] => 0
            [error] => 
            [error_list] => Array
                (
                )

            [field_count] => 0
            [host_info] => 127.0.0.1 via TCP/IP
            [info] => 
            [insert_id] => 0
            [server_info] => 5.5.60-MariaDB
            [server_version] => 50560
            [stat] => Uptime: 1845718  Threads: 2  Questions: 210730  Slow queries: 0  Opens: 587  Flush tables: 2  Open tables: 396  Queries per second avg: 0.114
            [sqlstate] => 00000
            [protocol_version] => 10
            [thread_id] => 6008
            [warning_count] => 0
        )

)

session Object
(
    [storage:session:private] => 
    [db:protected] => 
)

1 个答案:

答案 0 :(得分:6)

您需要在调用父构造函数之前

class session extends chief {
    public function __construct($address=null) {
        parent::__construct(); // <--- HERE
        var_dump($this->db);
    }
}

从文档中

  

注意:如果子类定义了构造函数,则不会隐式调用父构造函数。为了运行父构造函数,需要在子构造函数内调用parent :: __ construct()。如果子级没有定义构造函数,则可以像常规的类方法一样从父类继承该子类(如果未声明为私有)。

http://php.net/manual/en/language.oop5.decon.php