欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP5中虚函数的实现方法分享

程序员文章站 2023-11-09 22:45:16
请看下面的代码: 复制代码 代码如下:
请看下面的代码:
复制代码 代码如下:

<?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' );