Alex
Alex

Reputation: 68406

How to not allow a sub-class method to be defined in PHP

How can I prevent the something method below to be created in the foo class ?

class fooBase{

  public function something(){

  }
}

class foo extends fooBase{

  public function __construct(){
    echo $this->something(); // <- should be the parent class method
  }

  public function something(){ 
    // this method should not be allowed to be created
  }
}

Upvotes: 2

Views: 80

Answers (3)

Ross
Ross

Reputation: 17967

You can use final to prevent base methods being overwritten.

class fooBase{

  final public function something(){

  }
}

Upvotes: 2

SamT
SamT

Reputation: 10610

Use the final keyword.

In your parent:

final public function something()

Upvotes: 2

MGwynne
MGwynne

Reputation: 3522

Use the final keyword (like in Java etc):

class fooBase{

  final public function something(){

  }
}

class foo extends fooBase{

  public function __construct(){
    echo $this->something(); // <- should be the parent class method
  }

  public function something(){ 
    // this method should not be allowed to be created
  }
}

See PHP Final keyword. Note that foo will still have a method something, but something will only come from fooBase and foo can't override it.

Upvotes: 10

Related Questions