doujianjian2060 2012-11-01 20:33
浏览 94
已采纳

子类不从父类继承属性

This isn't working the way I thought it would. Here are my classes:

class App {
    public $db;

    public function __construct($db) {
        $this->db = $db;
    }
}

class Analysis extends App {

    public $analysis_id;

    public function __construct($analysis_id) {
        $this->analysis_id = $analysis_id;
    }
}

class Standard extends Analysis {

    public function __construct($analysis_id) {
        parent::__construct($analysis_id);
    }
}

$db is my database (mysqli) object that I've passed to the App class.

When I try to perform a new Standard Analysis, I initiate it like this:

$analysis = new Standard($analysis_id);

The Analysis class contains methods that retrieve meta data about an analysis, while the Standard class contains methods that retrieve calculations for that specific type of analysis. I thought I would be able to access the $db object, but I can't from the Analysis or Standard class. Do I need to pass the $db object to the Standard class when I initiate it?

  • 写回答

2条回答 默认 最新

  • douwen7905 2012-11-01 20:35
    关注

    Your Analysis class needs to call the constructor on its parent, App. This doesn't happen by default. Because $db is a parameter of the App constructor, you will have to pass this in from the subclasses as well, and then call parent::__construct($db) from the Analysis constructor.

    Correct code:

    class App {
        public $db;
    
        public function __construct($db) {
            $this->db = $db;
        }
    }
    
    class Analysis extends App {
        public $analysis_id;
    
        public function __construct($analysis_id, $db) {
            $this->analysis_id = $analysis_id;
            parent::__construct($db);
        }
    }
    
    class Standard extends Analysis {
        public function __construct($analysis_id, $db) {
            parent::__construct($analysis_id, $db);
        }
    }
    
    $analysis = new Standard($analysis_id, $db);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢