PHP - 扩展方法就像扩展一个类 [英] PHP - extend method like extending a class
本文介绍了PHP - 扩展方法就像扩展一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个类:
class animal{
public function walk(){
walk;
}
}
class human extends animal{
public function walk(){
with2legs;
}
}
这样,如果我调用human-> 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;
}
}
但问题是,我有很多子类和不想把parent :: walk();进入每个孩子步行()。有没有办法我可以扩展一个方法,如我扩展一个类?没有重写,但真正扩展的方法。还是有更好的替代品?
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?
谢谢。
推荐答案
使用hook
和抽象
概念:
class animal{
// Function that has to be implemented in each child
abstract public function walkMyWay();
public function walk(){
walk_base;
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();
让孩子走路...
请参阅 模板方法模式 。
See Template method pattern.
这篇关于PHP - 扩展方法就像扩展一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文