1

I want to call a function of main class to a child class. But here child class is not directly connected with parent class . Please see my code below.

main-class.php

class Main_Class {
  
  public function __construct() {
    $this->include_files();
 }
 
 public function include_files(){
    include_once('first_class.php');
 }
 
 public function my_parent_function(){
    echo 'this is my super parent_function';
 }

}

first_class.php

class First_class {

  public function __construct() {
    $this->include_files_1();
 }
 
 public function include_files_1(){
    include_once('my_abstaract_class.php');
    include_once('second_class.php');
 }

}
 

my_abstaract_class.php

abstract class My_abstaract_class {

 ...
}

second_class.php

class Second_class extends My_abstaract_class {

  public function __construct() {
    $this->my_child_function();
 }
 
 public function my_child_function(){
    $this->my_parent_function();
 }

}

Here i want to call my_parent_function() inside second_class.php. How can I do this? When I tried $this->my_parent_function(); it's not working.

Abilash Erikson
  • 341
  • 4
  • 26
  • 55
  • I think you need to learn a little more about OOP and modern PHP. You cannot include a class into a method implementation like your example. The way to go is through a thing called inheritance or even object composition. – lucasvscn Feb 17 '22 at 03:31
  • thank you. But please note i have an existing code from that is coded in this way . I have my_parent_function that i need to call in Second_class . So i am looking a way to implement this. – Abilash Erikson Feb 17 '22 at 03:37
  • In this case, check the "traits" feature (https://www.php.net/manual/en/language.oop5.traits.php). another idea is to make "my_parent_function" a static method. anyways you'll need to refactor the code. – lucasvscn Feb 17 '22 at 03:41
  • the abstract class is unnecessary. Your `Second_class` should directly extend the `Main_class` for simplicity. Also, `include_once()` will not inherit functions if the included file is a class. – Raptor Feb 17 '22 at 04:05
  • hi Please note i can't modify the current code structure. I can add additional codes or i can modify codes of my_parent_function or my_child_function – Abilash Erikson Feb 17 '22 at 04:38
  • You define `my_parent_function()` in `Main_class`, but `Second_class` does not extend `Main_class` but , so unless you instantiate `Main_class` within `Second_class`, you won't be able to call that method. The whole thing is rather a mess, I'm afraid. – yivi Feb 17 '22 at 08:14
  • Is there any particular reason, why you are not using Composer's autoloader but instead loading classes manually? – tereško Feb 23 '22 at 19:45

0 Answers0