最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PHP5中虛函數(shù)的實(shí)現(xiàn)方法分享

 更新時(shí)間:2011年04月20日 23:30:49   作者:  
學(xué)過(guò)C++的人都應(yīng)該知道C++中有個(gè)虛函數(shù)的概念。而在php5中如何實(shí)現(xiàn)這個(gè)虛函數(shù)呢?
請(qǐng)看下面的代碼:
復(fù)制代碼 代碼如下:

<?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()調(diào)用了A::x(),而B(niǎo)::x()覆蓋了A::x(),那么當(dāng)調(diào)用B::y()時(shí),B::y()應(yīng)該調(diào)用A::x()還是 B::x()呢?在C++中,如果A::x()未被定義為虛函數(shù),那么B::y()(也就是A::y())將調(diào)用A::x(),而如果A::x()使用 virtual關(guān)鍵字定義成虛函數(shù),那么B::y()將調(diào)用B::x()。然而,在PHP5中,虛函數(shù)的功能是由 self 和 $this 關(guān)鍵字實(shí)現(xiàn)的。如果父類(lèi)中A::y()中使用 self::x() 的方式調(diào)用了 A::x(),那么在子類(lèi)中不論A::x()是否被覆蓋,A::y()調(diào)用的都是A::x();而如果父類(lèi)中A::y()使用 $this->x() 的方式調(diào)用了 A::x(),那么如果在子類(lèi)中A::x()被B::x()覆蓋,A::y()將會(huì)調(diào)用B::x()。

上例的運(yùn)行結(jié)果如下:
A::x() was called. A::y() was called. --
B::x() was called. A::z() was called.
virtual-function.php
復(fù)制代碼 代碼如下:

<?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' );

相關(guān)文章

最新評(píng)論

清新县| 邵阳县| 蒙自县| 峨眉山市| 陆良县| 建德市| 巴林左旗| 阜新| 无为县| 黑水县| 高阳县| 温州市| 巴彦县| 金华市| 临高县| 安多县| 广宗县| 大同县| 大冶市| 长寿区| 安塞县| 长宁县| 元阳县| 遂昌县| 商都县| 哈尔滨市| 长汀县| 东山县| 莲花县| 渭南市| 沭阳县| 南阳市| 武陟县| 运城市| 呈贡县| 绥宁县| 大同县| 灵璧县| 利津县| 股票| 淮阳县|