Search code examples
phpclassinheritancemethodsextend

How do I add more functionality to child method?


parent_says() method says something, now I want to add more functonality to parent_says() method but from inside child class. How do I do it?

    class Parent_class{
    function parent_says(){
        echo "HI. I'm parent!";
    }
}

class Child_class extends Parent_class{
    function parent_says(){
        //I want it to also says "HI. I'm parent!", that's inside parent method.
        echo "I say hello!";
    }
}

$Child_class = new Child_class;
$Child_class->parent_says();

Solution

  • Use parent:: to call the parent class' method first. E.g.

    class Child_class extends Parent_class{
        function parent_says(){
            parent::parent_says();
            echo "I say hello!";
        }
    }
    

    See here for more information.