0

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?

nhnkl122
  • 17
  • 4
  • _I want to call firstfunction on service by calling only the parent, so for example ParentClass:init()->firstclass();_ In this case, your structure looks flawed. Can you share a small code snippet of what you wish to do? – nice_dev May 25 '22 at 07:41
  • @nice_dev hey! i don't have any snippets cause I didn't start writing anything yet, I'm trying to think about the best way to approach it. I will explain what I'm trying to do, I got a BaseActivity class which has few child classes, MovieClass, WalkClass, GymClass, each one of them having different functions related to the specific activity, Im also having a service, what I'm trying to figure out is how I'm gonna be calling the child function, without making the function in the BaseActivity class. – nhnkl122 May 25 '22 at 07:53
  • Understood, you need generalized type. Is it ok if I share a small code snippet for demo purpose? I hope you can create object of child class in your Service class? – nice_dev May 25 '22 at 07:57
  • 1
    yeah ofc! @nice_dev – nhnkl122 May 25 '22 at 07:59

1 Answers1

1

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.

nice_dev
  • 17,053
  • 2
  • 21
  • 35