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