duanke0555 2011-02-18 10:01
浏览 128
已采纳

PHP子类访问父类中的对象

class bm_main {

    public $db;

    public function __construct(){

        $this->db = new db();
    }

}

class bm extends bm_main{

    public function __construct($id){
        $this->db = parent::$db;
            $this->db->save($id);
    }
}

How to access the $db object from parent class so i can use it in the child one

  • 写回答

1条回答 默认 最新

  • doubai9014 2011-02-18 10:04
    关注

    Call the parent constructor so the db class is instantiated:

        public function __construct($id) {
            parent::__construct();
            $this->db->save($id);
        }
    

    The $db property is inherited by the subclass, and is public, so you can access it using $this->db.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?