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

时间:2014-12-05 19:37:32

标签: php

我的ChildClass延伸到ParentClassParentClass有一个带有两个参数__construct('value2', ParentClass::COMMON)的构造函数。我正在尝试从子类中调用继承的newSelect()方法。到目前为止,它还没有成功。如何从NewSelect()拨打ChildClass?即使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

}

1 个答案:

答案 0 :(得分:1)

//你不能这样做

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

说实话,我甚至不知道你要做什么,但关于它的一切看起来都错了!