gpt4 book ai didi

php - 从继承类调用私有(private)方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:57:59 25 4
gpt4 key购买 nike

我想在我的简单 ORM 中用 PHP 实现一个钩子(Hook)系统:

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

这会导致 fatal error :

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

有道理。

我可以将范围更改为公开,但这看起来很丑陋:除了 Payment 之外,没有人与 before_save() 有任何关系。恕我直言,最好保密。

如何让 Record 调用继承自 Record 的类的私有(private)方法?

最佳答案

向您的Record 类添加一个虚拟before_save 函数,将其可访问性设置为 protected 。现在所有继承自 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();
}
}

关于php - 从继承类调用私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12603766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com