PHP Inheritance between class methods without over

2019-08-08 15:04发布

问题:

ok i have 2 classes

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

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

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

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>

is this possible?

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

回答1:

Edit: 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>";
    }
}

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.

This is called the Template method pattern

Old answer

Just add parent::say(); to the overloading method:

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

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.

See also the php manual about extending classes.