Php 子类的声明必须与父类兼容

Php 子类的声明必须与父类兼容,php,oop,Php,Oop,我知道对于抽象父类,子类应该具有相同的数据类型。但我没有宣布这样具体的事情。只是子类声明的一个函数。除了三角形类之外,所有其他子类都没有错误 abstract class Shape { abstract function getArea(); } class Square extends Shape { protected $length = 4; public function getArea () { return pow($this->l

我知道对于抽象父类,子类应该具有相同的数据类型。但我没有宣布这样具体的事情。只是子类声明的一个函数。除了三角形类之外,所有其他子类都没有错误

abstract class Shape {
    abstract function getArea();
}

class Square extends Shape {
    protected $length = 4;

    public function getArea () {
        return pow($this->length, 2);
    }
}

class Circle extends Shape {
    protected $radius = 5;

    public function getArea() {
        return M_PI * pow($this->radius, 2);
    }
}

class Triangle extends Shape {
    protected $base = 3;
    protected $height = 14;

    public function getArea($base, $height) {
        return .5 * $this->base * $this->height;
    }
}

(new Triangle)->getArea();
为什么它会让我犯以下错误

Triangle::getArea()的声明必须与Shape::getArea()兼容


您将收到一个错误,因为您的方法的示意图已更改。不应在方法中传递参数,而应在构造函数中传递:

class Triangle extends Shape {
    private $base;
    private $height;


    public function __construct($base, $height)
    {
        $this->base = (int) $base;
        $this->height = (int) $height;
    }

    public function getArea($base, $height) 
    {
        return 0.5 * $this->base * $this->height;
    }
}


$foo = new Triangle(4, 13);
echo $foo->getArea();
我还强烈建议您也修改其他类,以便将
$radius
$length
等参数也传递到各自的构造函数中。否则,您当前正在打破“打开-关闭”原则


您将收到一个错误,因为您的方法的示意图已更改。不应在方法中传递参数,而应在构造函数中传递:

class Triangle extends Shape {
    private $base;
    private $height;


    public function __construct($base, $height)
    {
        $this->base = (int) $base;
        $this->height = (int) $height;
    }

    public function getArea($base, $height) 
    {
        return 0.5 * $this->base * $this->height;
    }
}


$foo = new Triangle(4, 13);
echo $foo->getArea();
我还强烈建议您也修改其他类,以便将
$radius
$length
等参数也传递到各自的构造函数中。否则,您当前正在打破“打开-关闭”原则


使用
func\u get\u args
Triangle
类的
getArea
方法中,您已经声明此方法有两个必需参数,而父类的
getArea
方法没有必需参数-当然,它会告诉您声明是不同的。我甚至不明白为什么你在
getArea
方法中需要这两个参数,你没有使用它们……为什么它要给我一个“三角形声明::getArea()必须与Shape::getArea()兼容”。你在Shape抽象中把
getArea
函数定义为
getArea(),
getArea($base,$height)
在三角形类中。由于您要扩展形状抽象,函数必须匹配。@Eihwaz我不知道如何在类中添加func_get_参数。您能告诉我怎么做吗?我还是个新手。@Django忽略这一点。函数不需要任何参数。在
getArea中使用
func_get_参数e> 
Triangle
类的方法,您已经声明此方法有两个必需的参数,而父类“
getArea
方法没有必需的参数-当然它会告诉您声明是不同的。我甚至不明白为什么您在
getArea
方法中需要这两个参数,您没有使用他们…为什么它会向我抛出一个“三角形声明::getArea()必须与Shape::getArea()兼容。您有
getArea
函数,在Shape抽象中定义为
getArea()
,但在Triangle类中定义为
getArea($base,$height)
。由于要扩展形状抽象,函数必须匹配。@Eihwaz我不知道如何在类中添加func_get_参数。你能告诉我怎么做吗?“我还是个新手。”Django别理它。该函数不需要任何参数。