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方法时为新加入的参数指定一个默认值即可。

posted @ 2012-03-30 11:41  有梦就能实现  阅读(14558)  评论(2编辑  收藏  举报