Search code examples
phpobject-oriented-analysis

OOP - How to make a parent function perform some default functionality?


In PHP, I have an abstract class (parent) which is extended by the child class. I want the child class to implement a function of parent. And when I call the implemented function of child, a default functionality of parent should be invoked automatically. Is it possible?

For example, I want to create parent's log function every time a send function of child is invoked.

abstract class CommunicationService {
    // child classes must implement this
    abstract function send();
    abstract function receive();

    public function log($action) {
        echo 'Creating nice Log on = ' . $action;
    }
}

class ServiceA extends CommunicationService {
    public function send() {
        // Is it possible that the parent's logging functionality be invoked automatically by default?
        echo 'Send Message using Service A';
    }
    public function receive() {
        echo 'Receive Message using Service A';
    }
}

$serviceA = new ServiceA();
$serviceA->send(); // It should send message as well as create logs.
$serviceA->receive(); // It should just receive message and not log it.

Also, is it possible to perform some default action in parent and the rest of the functionality in child?

best regards.


Solution

  • Any class which extends the parent needs its functions to explicitly call the parent log() function like this:

    public function send() {
        // Is it possible that the parent's logging functionality be invoked automatically by default?
        parent::log( 'some text' ); // Tell the parent to log
        echo 'Send Message using Service A';
    }