Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call private method from inherited class

I want to implement a hook-system in my simple ORM, in PHP:

class Record {
  public function save() {
    if (method_exists($this,"before_save")) {
      $this->before_save();
    }
    //...Storing record etc.
  }
}

class Payment extends Record {
  private function before_save() {
    $this->payed_at = time();
  }
}

$payment = new Payment();
$payment->save();

This results in a Fatal Error:

Fatal error: Call to private method Payment::before_save() from context 'Record' in

Makes sense.

I could change the scope to public, but that seems ugly: no-one but Payment has anything to do with before_save(). It is best left private, IMHO.

How can I make Record call a private method on the class inheriting from the Record?

like image 409
berkes Avatar asked Sep 26 '12 14:09

berkes


People also ask

Can we use private method in inherited class?

Private methods are inherited in sub class ,which means private methods are available in child class but they are not accessible from child class,because here we have to remember the concept of availability and accessibility.

Can we call private method from outside class?

You can call the private method from outside the class by changing the runtime behaviour of the class.

Can a child class use private methods from the parent?

Private methods of a parent class are not accessible to a child class.


1 Answers

Add a dummy before_save function to your Record class, set its accessibly to protected. Now all classes that inherit from Record will have this function, if they don't overwrite it it will do NOTHING. If they overwrite it, it can implement the desired functionality.

class Record {
  public function save() {
    $this->before_save();
    //...Storing record etc.
  }

  protected function before_save() {
     return;
  }
}

class Payment extends Record {
  protected function before_save() {
    $this->payed_at = time();
  }
}
like image 143
clentfort Avatar answered Oct 06 '22 00:10

clentfort