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


Proper way to access parent's methods in child class

我有一个扩展到ParentClassChildClassParentClass有一个构造函数,该构造函数__construct('value2', ParentClass::COMMON)接受两个参数。无论我尝试从子类中调用继承的newSelect()方法。到目前为止,它还没有成功。我该如何从ChildClass中称呼NewSelect()?即使ParentClass有一个接受两个参数的构造函数,是否有可能?

父母

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
 }

}

孩子

class ChildClass extends ParentClass {    

    public function __construct() {
    }
    // Call the inherited method
    private $_select = Parent::newSelect();
    // Do something with it
}

//你不能这样做

private $_select = Parent::newSelect();

试试这个

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

//和

$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

老实说,我什至不知道你想做什么,但关于它的一切看起来也错了!