我只是想计算返回其面积的矩形类之外的矩形面积的价格。只是尝试一个多态性的例子。我做错了什么吗?我是OOP的新手。这是我的代码:
// getting the area
class Rectangle{
public $height;
public $width;
public function __construct($height, $width){
$this->height = $height;
$this->width = $width;
}
public function getArea(){
return $this->height * $this->width. "<br />";
}
}
在类之外,我创建了函数'getPrice()
`function getPrice(Rectangle $rectangle){
return $rectangle->getArea() * 0.25;
}
创建实例并打印出来。
$rectangle = new Rectangle(12, 15);
echo getPrice();
显示的错误是:
可捕获的致命错误:传递给 getPrice() 的参数 1 必须是 Rectangle 的实例,没有给出,在第 41 行的/var/www/html/crashcourse/oop_php/phpacademy/polymorphism 中调用.php并在/var/www/html/crashcourse/oop_php/phpacademy/polymorphism.php 第 31 行定义
查找 getPrice () 函数有一个 $ 矩形参数,类型为 Rectangle 类,您需要传递实例化类的 Rectangle 对象。执行以下操作:
$ rectangle = new Rectangle (12, 15);
echo getPrice ($ rectangle);