PHP5中虚函数的实现方法分享
请看下面的代码:
该例中,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()。
上例的运行结果如下:
A::x() was called. A::y() was called. --
B::x() was called. A::z() was called.
virtual-function.php
代码如下:
<?php class A { public function x() { echo "A::x() was called.\n"; } public function y() { self::x(); echo "A::y() was called.\n"; } public function z() { $this->x(); echo "A::z() was called.\n"; } } class B extends A { public function x() { echo "B::x() was called.\n"; } } $b = new B(); $b->y(); echo "--\n"; $b->z(); ?>
该例中,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()。
上例的运行结果如下:
A::x() was called. A::y() was called. --
B::x() was called. A::z() was called.
virtual-function.php
代码如下:
<?php class ParentClass { static public function say( $str ) { static::do_print( $str ); } static public function do_print( $str ) { echo "<p>Parent says $str</p>"; } } class ChildClass extends ParentClass { static public function do_print( $str ) { echo "<p>Child says $str</p>"; } } class AnotherChildClass extends ParentClass { static public function do_print( $str ) { echo "<p>AnotherChild says $str</p>"; } } echo phpversion(); $a=new ChildClass(); $a->say( 'Hello' ); $b=new AnotherChildClass(); $b->say( 'Hello' );
相关推荐
tangjikede 2020-04-30
一个逗逗 2020-04-16
DreamsofJAVAD 2010-12-18
涂有薄技涂宗勋 2010-12-12
littleFatty 2019-05-30
继承对象模型在 C++ 编译器的内部类可以理解为结构体子类是由父类成员叠加子类新成员得到的class Dervied : public Demo. << "mk = " << mk << endl;c
lmmy 2019-06-30
智小星 2019-06-28
聚风阁 2010-08-12
独孤依人 2019-06-26
abserver 2018-08-28
hellokobe 2018-08-02
huiqinbo 2018-06-18
ygreatred 2018-09-05
zuihaobushi 2012-12-31
fkuevip 2018-09-12
丁一鸣的CSDN 2018-02-24
kevinzhangwen 2016-10-07
StrugglingDog 2010-02-05