继承——如何在父方法的中间添加子代码


Inheritance - how to add child code in the middle of a parent method?

我有以下类(这里简化了,所以没有测试):

class FATHER {
    protected function getDatas() {
        $this->query = "SELECT * FROM somewhere WHERE year = ? AND id_smthg = ? ";
        $this->param = array($_GET['year'], $_SESSION['anId']);
        // if $this is a FATHER
        if (get_called_class() == get_class())
            DB::getDatas($this->query, $this->$params);
    }
}
class CHILD extends FATHER {
    protected function getDatas() {
        parent::getDatas();
        foreach ($this->conditions as $condition) {
            $this->query .= " AND $condition->name = ? ";
            $this->param .= array($condition->value);
        }
        DB::getDatas($this->query, $this->params);
    }
}

子方法只是向父方法的查询添加SQL条件,然后执行请求。但是DB调用是冗余的,并且需要在父方法中使用if语句。

所以我想知道推荐的方法是什么?

我想象这样的事情,但我不知道怎么做:

class FATHER {
    protected function getDatas() {
        $this->query = "SELECT * FROM somewhere WHERE year = ? AND id_smthg = ? ";
        $this->param = array($_GET['year'], $_SESSION['anId']);
        // Make the child execution here
        DB::getDatas($this->query, $this->$params);
    }
}

也许这是不可能的,或者也许有更好的设计模式来做到这一点?

你可以使用抽象,这样你就可以用子代码重写父方法它将被称为

你可以在这里阅读

abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();  //this kind of methods you should implement in child
    abstract protected function prefixValue($prefix);
    // Common method
    public function printOut() {
        print $this->getValue() . "'n";
   }

}