【问题标题】:PHP Child class accessing object in Parent classPHP子类访问父类中的对象
【发布时间】:2011-06-29 17:18:54
【问题描述】:
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);
    }
}

如何从父类访问 $db 对象,以便我可以在子类中使用它

【问题讨论】:

    标签: php oop scope


    【解决方案1】:

    调用父构造函数,以便实例化db 类:

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

    $db 属性由子类继承,并且是公共的,因此您可以使用$this->db 访问它。

    【讨论】:

    • 谢谢,但我不能这样做,因为父构造函数调用了其他方法,我不会调用任何其他建议
    • @Stasa: -翻白眼-你可以这么说...将你的$this->db = new db();移到它自己的方法并让你的父母子构造函数调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多