Home > database >  Calling child function using parent
Calling child function using parent

Time:05-25

Hey guys got an architecture problem, I will explain the structure first

Service:

  • TestService

Classes:

  • InterfaceClass
  • ParentClass
  • FirstChildClass
  • SecondChildClass
  • ThirdChildClass

The Parent implements the interfaceClass and the childs extends the parentClass.

all childs have different functions, lets say firstfunction on FirstChildClass, secondfunction on SecondChildClass,

i want to call firstfunction on serice by calling only the parent, so for example ParentClass:init()->firstclass();

the language im gonna be using is PHP, anyone have any idea how can I implement such thing?

CodePudding user response:

You will need a generalized reference variable(of the base superclass) in your Service class constructor to achieve this. It is called generalization and widening. In programming terms, we call it Upcasting.

BaseActivity class

class BaseActivity{
    function base(){
        echo "from base", PHP_EOL;
    }
}

MovieClass class

class MovieClass extends BaseActivity{
    function movie(){
        echo "from MovieClass", PHP_EOL;
    }
}

WalkClass class

class WalkClass extends BaseActivity{
    function walk(){
        echo "from WalkClass", PHP_EOL;
    }
}

Service class

class Service{
    public $activity;
    function __construct(BaseActivity $b){ // here you have the base generalized reference of your hierarchy
        $this->activity = $b;
    }
}

Driver Code:

<?php

$service_A = new Service(new MovieClass());
$service_A->activity->movie();


$service_B = new Service(new WalkClass());
$service_B->activity->walk();

Online Demo

Note: So whenever you pass the object to the Service class constructor, it has to be a type of BaseActivity.

  • Related