【发布时间】:2017-11-04 05:41:26
【问题描述】:
我在 PHP 的 OOP 中遇到了一个问题。我试图实现一个抽象的父类方法,并且从子类中,我必须将它与可变数量的参数一起使用。
这是抛出的错误:
PHP 致命错误:Square::getArea($length) 的声明必须与 Shape::getArea() 兼容
还有课程:
abstract class Shape {
abstract protected function getArea();
}
class Square extends Shape {
public function getArea($length)
{
return pow($length, 2);
}
}
class Triangle extends Shape {
public function getArea($base, $height)
{
return .5 * $base * $height;
}
}
我可以使用孩子的__construct() 方法在启动时设置不同形状的属性,但我想知道是否存在另一种方法并允许我定义变量参数列表。
提前致谢。
【问题讨论】:
-
I could use the child's __construct() methods to set the properties of the different shapes at the initiation time这确实是最好的方法 -
但是您也可以在
getArea()方法中使用func_get_args()而无需在方法定义中指定参数 -
我不太喜欢
func_get_args()。我觉得有点脏。正如您所说,我将保留构造方法,这是最好的方法。感谢 cmets @MarkBaker -
另一种选择是使用 splat 运算符对
getArea(... $dimensions)的所有getArea()方法(包括摘要中的方法)使用单个参数;其次是list($base, $height) = $dimensions;作为方法的第一行 -
还要注意,如果您的摘要中有空方法,那么您实际上并不是在制作抽象,而是在制作接口。
标签: php oop inheritance methods abstract