GTeixeira
GTeixeira

Reputation: 3

Removing/Overriding Constructor Statements (PHP)

I learned that I can use a parent's constructor in PHP with ParentClass::__construct();. I imagine it's not possible, but I want to be sure; can I override or remove an aspect of the copied constructor? In other words, if the parent's constructor was

public function __construct(){
  print "This is from the parent class";
  test();
}

public function test(){
  print "Remove this function when copying to child class";
}

is there any way that I can

public function __construct(){
  ParentClass::__construct();
  //override/remove/negate test() function in the copied construct.
}

Upvotes: 0

Views: 364

Answers (1)

Jeto
Jeto

Reputation: 14927

Right now, your object structure is like this:

class ParentClass {
  public function test(): void {}
}

class ChildClass extends ParentClass {
  // This class has access to test() through inheritance
}

What you could have instead:

class BaseClass { 
  // Here, have everything that's actually common between all subclasses
}

class ClassA extends BaseClass {
  public function test(): void {}
}

class ClassB extends BaseClass {
  // This class does not have access to test()
}

You could also mix in some interfaces, but that's the basic idea.

Upvotes: 1

Related Questions