重写是一个面向对象编程概念,类似于 PHP 中的类、对象、封装、多态、重载等概念。当派生类中创建与基类或父类中的方法相同的方法时,就会完成函数和类的重写。这两个方法具有相同的名称和相同数量的参数。
广告 该类别中的热门课程 PHP 开发人员 - 专业化 | 8 门课程系列 | 3次模拟测试开始您的免费软件开发课程
网络开发、编程语言、软件测试及其他
让我们探索一下 PHP 中的重写是如何工作的。
方法重写的例子如下。
代码:
class BaseClass { public function ABC() { echo "<br /> In the base class"; } } class DerivedClass extends BaseClass { // override the method ABC() of base class public function ABC() { echo "<br />In the derived class"; } } $obj1 = new BaseClass; $obj1->ABC(); $obj2 = new DerivedClass; $obj2->ABC();
输出:
共有三个访问修饰符。
众所周知,受保护的方法可以从基类和派生类访问,它可以在子类中公开,但不能私有,因为私有方法只能在父类中访问。此外,如果类方法的访问说明符为 public,则派生类中的重写方法不能声明为 private 和 protected
下面写了一个使用访问修饰符进行覆盖的示例。
代码:
class BaseClass { private function ABC() { echo "<br/>In the base class Method : ABC"; } protected function XYZ() { echo "<br/>In the base class Method : XYZ"; } } class DerivedClass extends BaseClass { // overriding with public for wider accessibility public function ABC() { echo "<br/> In the derived class Method : ABC"; } // overriding method // with more accessibility public function XYZ() { echo "<br/>In the derived class Method : XYZ"; } } //$obj1 = new BaseClass; //$obj1->ABC(); //throws fatal error //$obj1->XYZ(); //throws fatal error $obj2 = new DerivedClass; $obj2->ABC(); $obj2->XYZ();
输出:
final 关键字用于类和方法。可以覆盖方法和类,而不是变量。
当一个方法或类被声明为final时,则无法对该方法或类进行重写,并且该类的继承也是不可能的。
使用final关键字覆盖的例子如下。
代码:
class BaseClass { // Final method – display // this cannot be overridden in base class final function display() { echo "<br /> In the Base class display function"; } /// method - ABC function ABC() { echo "<br /> In the Base cLass ABC function"; } } class DerivedClass extends BaseClass { function ABC() { echo "<br /> In the Derived class ABC function"; } } $obj1 = new DerivedClass; $obj1->display(); $obj1->ABC();
输出:
A class declared as final cannot be inherited. A Final Class further have final method along with other methods. But since the class itself is declared final there is no use of declaring a final method in a final class.
The example of class overriding using final keyword is written below.
Code:
// class declared as final cannot be overridden final class BaseClass { // method - ABC function ABC() { echo "<br> In the BaseClass Method ABC function"; } // Final method - display function display() { echo "<br> In the BaseClass Method display function"; } } // here you cannot extend the base class // as the base class is declared as final $obj1 = new BaseClass; $obj1->display(); $obj1->ABC();
Output:
以上是在 PHP 中重写的详细内容。更多信息请关注PHP中文网其他相关文章!