1

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

is there any other way that I will not need to use parent?
ok thank you.. hmm...but can you give me some advice? because I want to create a class that its methods will not be overloaded.. or if its not really possible ok i understand ^^
@Mahan Why would you not want to use parent?
because my teammates would have tendencies not to write it, what i really want here is to create a method that will run along the say() method if its invoked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.