phpoop

Child function which calls parent abstract function?


Is it possible to have a child function which calls a parent abstract function of the same name? In other words, I want the parent's function to be abstract so that it forces every child class to implement it. However, I don't want to completely override the parent's function, I want to be able to call it within the child's. Something like this:

class Parent {
    abstract function doSomething() {
        $do = true;
    }
}

class Child extends Parent {
    function doSomething() {
        parent::doSomething(); // sets $do = true
        $also_do = true;
    }
}

Solution

  • Asbract methods cannot have a body

    abstract function doSomething();
    

    If you want it to have a body, you must not declare it abstract. If you want to force child classes to stricly override an existing method, then there is something wrong with your design, or you should introduce another method (e.g. abstract function doSomethingChildSpecific()).

    However, its possible to call the overridden method the way you already do it.