请看下面的代码:
复制代码 代码以下:
<?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' );