PHP - 扩展方法,如扩展类

2022-08-30 22:02:59

我有2个班级:

class animal{
    public function walk(){
        walk;
    }
}

class human extends animal{
    public function walk(){
        with2legs;
    }
}

这样,如果我调用human->walk(),它只运行2legs;

但我想跑父母的路;太。

我知道我可以这样修改它:

class human extends animal{
    public function walk(){
        parent::walk();
        with2legs;
    }
}

但问题是,我有很多子类,我不想把parent::walk();走进每个孩子走路()。有没有办法像扩展类一样扩展方法?不覆盖,但真正扩展方法。还是有更好的选择?

谢谢。


答案 1

我会使用和概念:"hook"abstraction

class animal{

    // Function that has to be implemented in each child
    abstract public function walkMyWay();

    public function walk(){
        walk_base;
        $this->walkMyWay();
    }
}

class human extends animal{
    // Just implement the specific part for human
    public function walkMyWay(){
        with2legs;
    }
}

class pig extends animal{
    // Just implement the specific part for pig
    public function walkMyWay(){
        with4legs;
    }
}

这样我只需要调用:

// Calls parent::walk() which calls both 'parent::walk_base' and human::walkMyWay()
$a_human->walk();      
// Calls parent::walk() which calls both 'parent::walk_base' and pig::walkMyWay()
$a_pig->walk();

让一个孩子走他的路...


请参阅模板方法模式



答案 2

推荐