我想在我的简单 ORM 中用 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();
这会导致致命错误:
致命错误:调用私有方法 Payment::before_save()
上下文“记录”于
说得通。
我可以将范围更改为公开,但这看起来很难看:除了付款之外没有人与before_save()
。恕我直言,最好将其保留为私有。
如何让 Record 调用继承 Record 的类上的私有方法?
添加一个虚拟人before_save
功能到你的Record
类,将其可访问地设置为受保护。现在所有继承自的类Record
将具有此功能,如果他们不覆盖它,它将不会执行任何操作。如果他们覆盖它,它就可以实现所需的功能。
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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)