从继承的类中调用私有方法 [英] Call private method from inherited class

查看:109
本文介绍了从继承的类中调用私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这将导致致命错误:

严重错误:从以下方法调用私有方法Payment :: before_save() 上下文记录"于

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

有道理.

我可以将范围更改为公开,但是这看起来很丑:没有人,但付款与before_save()有关.最好还是私下,恕我直言.

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.

如何在从Record继承的类上使Record调用私有方法?

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

推荐答案

向您的Record类添加一个虚拟before_save函数,并将其可访问性设置为protected.现在,所有从Record继承的类都将具有此功能,如果他们不覆盖它,它将没有任何作用.如果他们覆盖它,它可以实现所需的功能.

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

这篇关于从继承的类中调用私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆