我正在尝试使用函数向类中的公共变量添加值。我不确定该怎么做。我目前的PHP代码如下:
class Truck {
public $Odometer = 0;
public $Model = 'Triton';
public $Price;
public $Horsepower;
public function __construct() {
$this->Price = 30;
}
public function __construct() {
$this->Horsepower = 205;
}
public function ShowOdometer() {
echo "Odometer: ".$this->Odometer;
}
public function ShowModel() {
echo "Model: ".$this->Model;
}
public function ShowPrice() {
echo "Cost: ".$this->Price;
}
public function ShowHorsepower() {
echo "Horsepower: ".$this->Horsepower
}
}
我试图通过一种方法为$ Price和$ Horsepower添加一个整数值。我试图使用__construct(),虽然这给了我一个致命的错误:Cannot redeclare Truck::__construct().
答案 0 :(得分:2)
您在constructor
内定义了两个class
,因此错误为Fatal error: Cannot redeclare Truck::__construct()
。试试 -
class Truck {
public $Odometer = 0;
public $Model = 'Triton';
public $Price;
public $Horsepower;
public function __construct() {
$this->Price = 30;
$this->Horsepower = 205;
}
public function ShowOdometer() {
echo "Odometer: ".$this->Odometer;
}
public function ShowModel() {
echo "Model: ".$this->Model;
}
public function ShowPrice() {
echo "Cost: ".$this->Price;
}
public function ShowHorsepower() {
echo "Horsepower: ".$this->Horsepower
}
}