PHP 物件導向 final類與final方法

來源:互聯網
上載者:User

標籤:

final---用於類、方法前。

final類---不可被繼承。

final方法---不可被覆蓋。

如果我們不希望一個類被繼承,我們使用final來修飾這個類。這個類將無法被繼承。

比如我們設定的Math類,涉及了我們要做的數學計算方法,這些演算法也沒有必要修改,也沒有必要被繼承,我們把它設定成final類型。

 1 <?  2 //聲明一個final類Math  3 final class Math 4 {  5     public static $pi = 3.14;  6  7     public function __toString() 8     {  9         return "這是Math類。"; 10     } 11 } 12 $math = new Math(); 13 echo $math; 14 15 //聲明類SuperMath 繼承自 Math類 16 class SuperMath extends Math 17 { 18 } 19 //執行會出錯,final類不能被繼承。 20 21 ?> 

程式運行結果 

Fatal error: Class SuperMath may not inherit from final class (Math) in E:\PHPProjects\test.php on line 16

如果不希望類中的某個方法被子類重寫,我們可以設定這個方法為final方法,只需要在這個方法前加上final修飾符。

如果這個方法被子類重寫,將會出現錯誤。

 1 <?  2 //聲明一個final類Math  3 class Math 4 {  5     public static $pi = 3.14;  6     public function __toString() 7     {  8         return "這是Math類。";  9     } 10   public final function max($a,$b)11   { 12       return $a > $b ? $a : $b ; 13   } 14 } 15 //聲明類SuperMath 繼承自 Math類 16 class SuperMath extends Math17 { 18     public final function max($a,$b){} 19 } 20 //執行會出錯,final方法不能被重寫。 21 22 ?> 

程式運行結果 

Fatal error: Class SuperMath may not inherit from final class (Math) in E:\PHPProjects\test.php on line 16

 

PHP 物件導向 final類與final方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.