php虚办法的完成:起首创立一个PHP示例文件;而后经过“<?php public function x() { echo "A::x() was called.\n"; public function y(){...}}”形式完成虚函数。
保举:《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虚办法怎样完成的具体内容,更多请存眷资源魔其它相干文章!
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!