冰镇可乐 发表于 2015-8-30 09:40:47

php 方法重写,参数不同,报错: Declaration of should be compatible with that

  问题详细描述为:https://bugs.php.net/bug.php?id=46851

[*]
<?php
[*]
abstract class A {
[*]
// 方法无参数
[*]
public static function foo(){ echo 'bar'; }
[*]
}
[*]
[*]
abstract class B extends A {
[*]
// 方法有参数
[*]
public static function foo($str){ echo $str; }
[*]
}
[*]
?>
  
如上面的代码:类A中的foo方法无参数,类B在继承A后重写foo方法时加入了参数,因此会产生一个类似下面E_STRICT级别的警告:
Strict standards: Declaration of ... should be compatible with that of ...  
解决方法:

[*]
<?php
[*]
abstract class A {
[*]
// 方法无参数
[*]
public static function foo(){ echo 'bar'; }
[*]
}
[*]
[*]
abstract class B extends A {
[*]
// 方法有参数
[*]
public static function foo($str = NULL){ echo $str; }
[*]
}
[*]
?>
  
类B在重写foo方法时为新加入的参数指定一个默认值即可。
页: [1]
查看完整版本: php 方法重写,参数不同,报错: Declaration of should be compatible with that