Return values through a class derived from the same Parent

Asked

Viewed 238 times

2

I have classes 1, 2a and 2b, where 1 is the main class, while 2a and 2b extends class 1. It is possible through class 2a to access values of class 2b directly or through the parent class?

Basic example:

class system{
}

class modulos extends system{

    function __construct(){
        $exemple = controllers::exemple();
    }
}

class controllers extends system{

    public function exemple(){
        return true;
    }
}

$system = new system();
  • These values are public, protected or private?

  • You can enter the code of the classes?

2 answers

1

That way you did it is impossible. When modulos and controllers inherit from system each class follows a different path and the two do not relate.

Whether there is a common method that will be used by all classes that inherit from system, then by logic who should contain this method is system.

class system{
    protected function exemple() {
        return true;
    }
}

class modulos extends system{

    function __construct(){
        $exemple = this->exemple();
    }
}

class controllers extends system{}

$system = new system();

There are other ways to solve this, but all including the one I gave above will depend on how you want the relationship between your classes to be.

0

Hello!

As the class 2b(controllers) is a dependency of class 2a(modules), I believe that the constructor of 2a should receive obligatorily a reference of 2b.

I would do it this way:

class modulos extends system{

  function __construct($controllers){
      $exemple = $controllers::exemple();
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.