简体   繁体   English

在子类中访问父方法的正确方法

[英]Proper way to access parent's methods in child class

I have a ChildClass that extends to a ParentClass . 我有一个ChildClass延伸到一个ParentClass The ParentClass has a constructor that takes two arguments __construct('value2', ParentClass::COMMON) . ParentClass具有一个带有两个参数__construct('value2', ParentClass::COMMON)的构造函数。 HOwever I am trying to call the inherited newSelect() method from within the child class. 但是,我试图从子类中调用继承的newSelect()方法。 So far it has not been succesfull. 到目前为止,还没有成功。 How would I call NewSelect() from the ChildClass ? 我如何从ChildClass调用NewSelect() Also is it possible even though the ParentClass has a constructor that takes two parameters? 即使ParentClass的构造函数带有两个参数,这也是可能的吗?

Parent

class ParentClass {    

const COMMON = 'common';

protected $db;

protected $common = false;

protected $quotes = array(
'Common' => array('"', '"'),
'Value2' => array('`', '`'),
'Value3' => array('`', '`'),
'Value4' => array('`', '`'),
);

protected $quote_name_prefix;

protected $quote_name_suffix;

   public function __construct($db, $common = null) {
    $this->db = ucfirst(strtolower($db));
    $this->common = ($common === self::COMMON);
    $this->quote_name_prefix = $this->quotes[$this->db][0];
    $this->quote_name_suffix = $this->quotes[$this->db][1];
   }

 public function newSelect() {
    return $this->newInstance('Select');
 }

 protected function newInstance($query) {
    //Some more code,  not relevant to example
 }


}

Child 儿童

class ChildClass extends ParentClass {    



    public function __construct() {

    }

    // Call the inherited method

    private $_select = Parent::newSelect();

    // Do something with it

}

// you can't do this //您无法执行此操作

private $_select = Parent::newSelect();

// try this // 尝试这个

private $_select;

public function construct($value, $common)
{
    Parent::__construct($value, $common);
    $this->_select = $this->newSelect();
}

// and //和

$obj = new ChildClass('Value2', ParentClass::COMMON); //  ParentClass::COMMON - not sure why you would do this
$select = $obj->newSelect(); // this is being called in constructor, why call it again

and to be honest, I don't even know what you're trying to do but everything about it looks wrong too! 老实说,我什至不知道您要做什么,但是有关它的一切看起来也都错了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM