PHP - 扩展类扩展方法

时间:2013-06-18 03:38:24

标签: php class extends

我有2个课程:

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

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

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

但我希望父母的行走;太

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

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

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

感谢。

1 个答案:

答案 0 :(得分:25)

我会使用"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();

让孩子走自己的路......


请参阅 Template method pattern