当前位置:Gxlcms > PHP教程 > php中虚函数的实现方法

php中虚函数的实现方法

时间:2021-07-01 10:21:17 帮助过:60人阅读

虚函数为了重载和多态的需要,在基类中是由定义的,即便定义是空,所以子类中可以重写也可以不写基类中的函数!

纯虚函数在基类中是没有定义的,必须在子类中加以实现,很像java中的接口函数!

虚函数

引入原因:为了方便使用多态特性,我们常常需要在基类中定义虚函数。

而在php5中如何实现这个虚函数呢?请看下面的代码:

  1. <?php
  2. class A {
  3. public function x() {
  4. echo "A::x() was called.\n";
  5. }
  6. public function y() {
  7. self::x();
  8. echo "A::y() was called.\n";
  9. }
  10. public function z() {
  11. $this->x();
  12. echo "A::z() was called.\n";
  13. }
  14. }
  15. class B extends A {
  16. public function x() {
  17. echo "B::x() was called.\n";
  18. }
  19. }
  20. $b = new B();
  21. $b->y();
  22. echo "--\n";
  23. $b->z();
  24. ?>

该例中,A::y()调用了A::x(),而B::x()覆盖了A::x(),那么当调用B::y()时,B::y()应该调用A::x()还是 B::x()呢?在C++中,如果A::x()未被定义为虚函数,那么B::y()(也就是A::y())将调用A::x(),而如果A::x()使用 virtual关键字定义成虚函数,那么B::y()将调用B::x()。然而,在PHP5中,虚函数的功能是由 self 和 $this 关键字实现的。如果父类中A::y()中使用 self::x() 的方式调用了 A::x(),那么在子类中不论A::x()是否被覆盖,A::y()调用的都是A::x();而如果父类中A::y()使用 $this->x() 的方式调用了 A::x(),那么如果在子类中A::x()被B::x()覆盖,A::y()将会调用B::x()。
上例的运行结果如下:

  1. A::x() was called. A::y() was called. --
  2. B::x() was called. A::z() was called.

virtual-function.php

  1. <?php
  2. class ParentClass {
  3. static public function say( $str ) {
  4. static::do_print( $str );
  5. }
  6. static public function do_print( $str ) {
  7. echo "<p>Parent says $str</p>";
  8. }
  9. }
  10. class ChildClass extends ParentClass {
  11. static public function do_print( $str ) {
  12. echo "<p>Child says $str</p>";
  13. }
  14. }
  15. class AnotherChildClass extends ParentClass {
  16. static public function do_print( $str ) {
  17. echo "<p>AnotherChild says $str</p>";
  18. }
  19. }
  20. echo phpversion();
  21. $a=new ChildClass();
  22. $a->say( 'Hello' );
  23. $b=new AnotherChildClass();
  24. $b->say( 'Hello' );

以上就是php 中虚函数的实现方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行