首頁  >  文章  >  後端開發  >  php虛方法怎麼實現

php虛方法怎麼實現

藏色散人
藏色散人原創
2020-10-09 09:53:471849瀏覽

php虛擬方法的實作:先建立PHP範例檔;然後透過「01d9714d03c3b7a54b0f8abd97c089f2x() 的方式呼叫了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( &#39;Hello&#39; ); 
$b=new AnotherChildClass(); 
$b->say( &#39;Hello&#39; );

以上是php虛方法怎麼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn