PHP Strict standards:Declaration of … should be compatible with that of…子类重写基类方法时报错问题。
今天在写子类代码继承写父类方法时,报了 PHP Strict standards:Declaration of … should be compatible with that of…这类型错误,字面上意思是方法不匹配,查找了诸多帖子都是说继承类要在父类之后定义。然并卵,没什么卵用。
真正原因:
真正的原因是因为子类重写方法与基类方法参数不一致导致的。使用过JAVA或者C++的程序员都知道,重写方法的函数签名本应该就和基类函数是一致的,这也是符合规律的,因为override就是覆盖的意思,既然是覆盖了,那么就应该和原函数保持一致,并且方法的重写多用在重写虚函数或者更明白的说就是重写接口的函数,如果重写的时候函数签名都不一致了,还要接口干嘛。
其实如果子类重写方法的参数和基类不一样,只要给参数个默认值,使得编译器认为参数可以为空,保持重写方法与基类方法的函数签名相同就可以了。
特此做了以下测试:
<?php
abstract class Base
{
function __construct()
{
# code...
}
// 方法无参数
public static function foo(){
echo 'bar';
}
}
abstract class Test extends Base{
// 方法有参数
public static function foo($str){
echo $str;
}
}
?>
此时类Test继承基类Base ,运行将报错:
代码修改只需保持一致性原则即可,可以给子类参数赋初值,也可以删除子类参数(如果你不需要时)
<?php
abstract class Base
{
function __construct()
{
# code...
}
// 方法无参数
public static function foo(){
echo 'bar';
}
}
abstract class Test extends Base{
// 方法有参数
public static function foo($str = ''){
echo $str;
}
}
?>