我正在用 PHP 创建一个报告库,并开发了一个名为 ReportView 的抽象类。这将提供报告的基本功能,如生成页眉和页脚、创建参数表单。
在这个类中还有一个名为generate_report 的函数。目前它在抽象类中是空的,因为在这个级别我们不知道报告的内容。此外,它还包含一个 render 函数,该函数调用此 generate_report 函数并将输出发送到浏览器。
So I need whenever a child class inherits from ReportView it must implement the generate_report method otherwise PHP must give error. Is there any keyword or method through which we can enforce implemetation of a specific function.
最佳答案
执行以下操作:
abstract class ReportView {
abstract protected function generate_report();
// snip ...
}
class Report extends ReportView {
protected function generate_report() { /* snip */ }
}
任何扩展 ReportView
且不是抽象的类必须实现generate_report
(以及与此相关的父类(super class)中的任何其他抽象函数) .
关于php - 强制子类覆盖 PHP 中的特定函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16842564/