php:mysql对象不能被子类访问

zsbz8rwp  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(380)

使用函数 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] => 
)
jtoj6r0c

jtoj6r0c1#

您需要在以下操作之前调用父构造函数:

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

从文档中:
注意:如果子类定义构造函数,则不会隐式调用父构造函数。为了运行父构造函数,需要在子构造函数中调用parent::\u construct()。如果子类没有定义构造函数,那么它可以像普通类方法一样从父类继承(如果它没有声明为private)。
http://php.net/manual/en/language.oop5.decon.php

相关问题