PHP - 扩展方法,如扩展类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17160160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:24:27  来源:igfitidea点击:

PHP - extend method like extending a class

phpclassextends

提问by Tony

I have 2 class:

我有2个班级:

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

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

This way, if i call human->walk(), it only runs with2legs;

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

But I want the run the parent's walk; too.

但我想要跑父母的步行;也。

I know I can modify it this way:

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

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

But the problem is, I have many subclasses and I don't want to put parent::walk(); into every child walk(). Is there a way I can extend a method like I extend a class? Without overriding but really extending the method. Or is there better alternatives?

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

Thanks.

谢谢。

回答by Gauthier Boaglio

I would use "hook"and abstractionconcepts :

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

This way I just have to call :

这样我只需要打电话:

// 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();

to make a child walk his way...

让孩子走他的路……



See Template method pattern.

请参阅模板方法模式