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?
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.
You can call the private method from outside the class by changing the runtime behaviour of the class.
Private methods of a parent class are not accessible to a child class.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With