PHP - extend method like extending a class

我是研究僧i 提交于 2020-01-01 07:57:25

问题


I have 2 class:

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;

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?

Thanks.


回答1:


I would use "hook" and abstraction concepts :

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.




来源:https://stackoverflow.com/questions/17160160/php-extend-method-like-extending-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!