PHP5中虚函数的实现方法分享
前端之家收集整理的这篇文章主要介绍了
PHP5中虚函数的实现方法分享,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请看下面的代码:
<div class="codetitle"><a style="CURSOR: pointer" data="16517" class="copybut" id="copybut16517" onclick="doCopy('code16517')"> 代码如下:
<div class="codebody" id="code16517">
<?
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
<div class="codetitle">
<a style="CURSOR: pointer" data="8231" class="copybut" id="copybut8231" onclick="doCopy('code8231')"> 代码如下: <div class="codebody" id="code8231">
<?
PHP class ParentClass {
static public function say( $str ) {
static::do_print( $str );
}
static public function do_print( $str ) {
echo "
Parent says $str
";
}
}
class ChildClass extends ParentClass {
static public function do_print( $str ) {
echo "
Child says $str
";
}
}
class AnotherChildClass extends ParentClass {
static public function do_print( $str ) {
echo "
AnotherChild says $str
";
}
}
echo
PHPversion();
$a=new ChildClass();
$a->say( 'Hello' );
$b=new AnotherChildClass();
$b->say( 'Hello' );