Skip to content
Advertisement

How to structure PHP classes [closed]

In file A,

Class A {
   __construct() {
          ...
      lots of code 
          ...
  }

  public function P() {
      code here
  }
}
New A();

In file B,

Class B {
   __construct() {
          ...
      lots of code 
          ...
  }

  public function E() {
      I need to call function P in Class A
  }
}
New B();

I would like to call the function P() in function E().

Is there any way to call a function in another class?

I found several ways such as dependency injection using __construct( A $aobj ) or “extends”

However, the class A was already instantiated in file A and there’re a lot of things in __counstruct so I would like to know

1) the way of refractory technique

2) fancy way to call function E() in function P().

Advertisement

Answer

It really depends on how class B is related to A :

  • no link : the function in A should be static (it doesn’t interact with a specific instance of A and its properties), and you can call A::P()

  • the class B is a child of A :

In B class definition, you have a class B extends A and in the constructor of B, you will have a parent::__construct() to call the constructor of A. Then you can simply call $this->P() : as B is a subclass of A, and P is public (or protected), B inherits of all methods from A

  • The class B uses a object of type A`

Then, you must have a $a attribute in the class B, and a $this->a = new A(); in the constructor of B. You can call P with $this->a->P();

Or if you need only temporarily A in E(), you can construct a new object $a = new A(); and call $a->P(); in the code of E

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement