Php 为什么子方法必须和父方法具有相同的参数?

Php 为什么子方法必须和父方法具有相同的参数?,php,overriding,Php,Overriding,我有以下代码: abstract class Base{ public function delete(){ // Something like this (id is setted in constructor) $this->db->delete($this->id); } } 然后我有另一个扩展Base的类,例如: class Subtitles extends Base{ public function delete($p

我有以下代码:

abstract class Base{

   public function delete(){
     // Something like this (id is setted in constructor)
     $this->db->delete($this->id);
   }

}
然后我有另一个扩展Base的类,例如:

class Subtitles extends Base{

    public function delete($parameter){
         parent::delete();
         // Do some more deleting in transaction using $parameter
    }

}
这也恰好有方法delete

问题来了:

当我打电话时

$subtitles->delete($parameter)
我得到:

Strict error - Declaration of Subtitles::delete() should be compatible with Base::delete() 
所以我的问题是,为什么我不能使用不同参数的后代方法


感谢您的解释。

若要重写基类中的函数,方法必须具有与其替换的方法相同的“签名”

签名由名称、参数(和参数顺序)和返回类型组成


这就是多态性的本质,也是面向对象编程获得其强大功能的地方。如果不需要重写父方法,请为新方法指定一个不同的名称。

这是因为PHP执行方法重写而不是方法重载。所以方法签名必须完全匹配

作为针对您的问题的工作,您可以将基类上的delete重新构造为

public function delete($id = null){
  // Something like this (id is setted in constructor)
  if ($id === null) $id = $this->id;
  $this->db->delete($id);
}

然后将子类方法签名更改为匹配

这是对@orangePill's ansert的评论,但我没有足够的声誉来评论

我对静态方法也有同样的问题,我使用。也许这对某人有帮助

abstract class baseClass {
    //protected since it makes no sense to call baseClass::method
    protected static function method($parameter1) {
        $parameter2 = static::getParameter2();

        return $parameter1.' '.$parameter2;
    }
}

class myFirstClass extends baseClass {
    //static value, could be a constant
    private static $parameter2 = 'some value';

    public static function getParameter2() {
        return self::$parameter2;
    }

    public static function method($parameter1) {
        return parent::method($parameter1);
    }
}

class mySecondClass extends baseClass {
    private static $parameter2 = 'some other value';

    public static function getParameter2() {
        return self::$parameter2;
    }

    public static function method($parameter1) {
        return parent::method($parameter1);
    }
}
用法


嗯,比这更复杂,但我明白了。谢谢。不幸的是,我需要重写这个方法,因为我想阻止:$subtitles->delete()只调用父方法。但是谢谢。
echo myFirstClass::method('This uses'); // 'This uses some value'

echo mySecondClass::method('And this uses'); // 'And this uses some other value'