PHP类方法之间的继承,而不重载它,只是合并它 [英] PHP Inheritance between class methods without overloading it, just merge it

查看:142
本文介绍了PHP类方法之间的继承,而不重载它,只是合并它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ok我有2个课程

class A{  
     public function say(){
        echo "hello<br>";
     }  
  }

 class B extends A{
    public function say(){
        echo "hi<br>";
    }
 }

 $haha = new B();
 $haha->say();

很好,因为你看到我重载方法say()在类b ...但我想要的这里是合并两个方法,而不是互相覆盖。我想要的输出是这个

well as you see i overloaded the method say() in class b... but what i want here is to merge the two methods and not overwrite each other. my desired output I want is this

hello<br>
hi<br>

这是否可能?

如果我的条款错了,请教我正确的条款。我真的是新的PHP OOP

NOTE: if my terms are wrong, please teach me the right terms. I am really new to PHP OOP

推荐答案

编辑:
根据您的意见,你想要这样的:

Based on your comments, you want something like this:

class A{
    final public function say(){
        echo "hello<br>";
        $this->_say();
    }

    public function _say(){
        //By default, do nothing
    }
}

class B extends A{
    public function _say(){
        echo "Hi<br>";
    }
}

我已经调用了新函数 _say ,但你可以给它任何你想要的名字。这样,你的队友只需要定义一个名为_say()的方法,它会自动被类 A 的say方法调用。

I have called the new function _say, but you can give it any name you want. This way, your teammates just define a method called _say(), and it will automatically be called by class A's say method.

这称为模板方法模式

旧答案

只需添加 parent :: say(); 到重载方法:

class B extends A{
    public function say(){
        parent::say();
        echo "hi<br>";
    }
 }

这告诉php执行重载的方法。如果您不希望扩展类重载其方法,可以将其声明为最后

This tells php to execute the overloaded method. If you don't want extending classes to overload it's methods, you can declare them final.

另请参阅有关 extend 类。

这篇关于PHP类方法之间的继承,而不重载它,只是合并它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆