Call private method from inherited class

berkes picture berkes · Sep 26, 2012 · Viewed 10.4k times · Source

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?

Answer

clentfort picture clentfort · Sep 26, 2012

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();
  }
}