【问题标题】:Working with extended classes in PHP在 PHP 中使用扩展类
【发布时间】:2012-04-09 01:07:14
【问题描述】:

我有 2 个类看起来像这样:

class db {

    protected $db;

    function __construct() {
        $this->connect();
    }

    protected function connect() {
        $this->db = new MySQLi(db_host, db_user, db_pass, db_name) or die($this->db->error);
        $this->db->set_charset('utf8');
    }

}

class sample extends db {

    protected $js_base_dir;

    public function __construct($js_base_dir = js_dir) {
        $this->js_base_dir = $js_base_dir . "/";
    }
 ....

我想在第二类中使用 $this->db,但是在 sample 类中的 __construct 会覆盖第一类构造函数。如何在二等舱内获得 $this-> db?我做错什么了吗?如果是的话,什么是正确的方法?

【问题讨论】:

  • 你的代码说“样本是一个数据库”......这听起来不对

标签: php class methods parameters extend


【解决方案1】:

试试这个:

public function __construct($js_base_dir = js_dir) {

    parent::__construct();

    $this->js_base_dir = $js_base_dir . "/";        
}

【讨论】:

  • 我想知道这是否正确?我可以用这种方式创建新课程吗?
  • 什么都不会改变,除了现在你的子类(示例)将调用它的父构造函数,它将初始化$this->db。您的呼叫代码不会改变。
  • 您觉得这个答案有帮助吗?
【解决方案2】:

你可以调用父类方法,使用parrent::methodName()。同样,您可以使用它来调用父级的构造方法以及

parent::__construct();

用法:

public function __construct($js_base_dir = js_dir) {
    parent::_construct();
    $this->js_base_dir = $js_base_dir . "/";
}

除了manual,阅读this 文章以获得更多解释。

【讨论】:

  • 我想知道这是否正确?我可以用这种方式创建新课程吗?
  • @epic_syntax,阅读this 文章以帮助解决问题。
  • "父::__construct();"而不是“parent::_construct();”
猜你喜欢
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 2012-06-27
  • 2012-07-31
  • 2013-02-06
  • 2017-01-09
相关资源
最近更新 更多