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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?