php虚方法的实现:首先创建一个php示例文件;然后通过“
推荐:《php视频教程》
php5中虚函数的实现方法分享
学过c++的人都应该知道c++中有个虚函数的概念。而在php5中如何实现这个虚函数呢?
请看下面的代码:
代码如下:
<?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' );
以上就是php虚方法怎么实现的详细内容。