php 方法重寫,參數不同,報錯: Declaration of should be compatible with that


問題詳細描述為:https://bugs.php.net/bug.php?id=46851

  1. <?php
  2. abstract class A {
  3. // 方法無參數
  4. public static function foo ( ) { echo 'bar' ; }
  5. }
  6.  
  7. abstract class B extends A {
  8. // 方法有參數
  9. public static function foo ( $str ) { echo $str ; }
  10. }
  11. ?>


如上面的代碼:類A中的foo方法無參數,類B在繼承A后重寫foo方法時加入了參數,因此會產生一個類似下面E_STRICT級別的警告:

Strict standards: Declaration of ... should be compatible with that of ...


解決方法:

  1. <?php
  2. abstract class A {
  3. // 方法無參數
  4. public static function foo ( ) { echo 'bar' ; }
  5. }
  6.  
  7. abstract class B extends A {
  8. // 方法有參數
  9. public static function foo ( $str = NULL ) { echo $str ; }
  10. }
  11. ?>


類B在重寫foo方法時為新加入的參數指定一個默認值即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM