PHP5中self与$this实现虚函数机制
参考以下代码示例:
具体代码如下:
<?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重写了A::x()。此时调用B::y()时,究竟执行的是A::x()还是B::x()?这与C++中的虚函数机制类似:若A::x()非虚函数,则B::y()调用A::x();若A::x()声明为virtual,则B::y()调用B::x()。但在PHP5中,这一效果由self和$this关键字控制。若父类A::y()采用self::x()方式调用,无论子类是否重写,均执行A::x();若采用$this->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 "
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' );