我试图创建一个类函数,但不知何故它不起作用,我无法弄清楚问题是什么。这是我声明变量的方式还是那样的?
<?php
class Car{
var $model;
var $make;
var $speed;
function Car ( $model, $make, $speed)
{
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
function accelerate ($speed)
{
$add = 5;
$speed = $speed + $add;
return $speed;
}
function get_status()
{
echo "Car status : \n";
echo "Model :" $this-> model "\n";
echo "Make :" $this-> make "\n\n";
}
function get_speed()
{
return $this->speed;
}
}
?>
<?php
$car1 = new Car();
$car1 -> get_status("Vios", "Toyota");
for( $i = 0; $i < 5 ; $i++)
{
echo "Accelerating... <br> \n";
echo "Current speed : accelerate(5) km/h <br>";
}
?>
答案 0 :(得分:1)
您的代码存在很多问题。但至少这个清理版本应该可以在没有脚本完全死亡的情况下工作。以下是我所做的细分:
var
的变量设置为public
,因为这是设置变量的首选方法。function Car
中,我为$model
,$make
&amp;设置了默认值。 $speed
所以,如果它们没有在您的示例中传递 - 至少有一个默认值可以作用。echo
中的get_status
行没有连接.
,因此它们没有正确连接字符串。$this-> make
和$this-> model
在语法上是不正确的。因此,请将其设置为$this->make
和$this->model
。"Current speed : accelerate(5) km/h <br>";
,这在语法上也是不正确的。因此,将其设置为echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
,以便它实际上可以回显值。但是那说,不清楚这段代码的输出是什么。逻辑有点混乱。但至少它并没有像以前那样彻底死亡!
这是清理过的代码:
class Car {
public $model;
public $make;
public $speed;
function Car ($model = 0, $make = 0, $speed = 0) {
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
function accelerate ($speed) {
$add = 5;
$speed = $speed + $add;
return $speed;
}
function get_status () {
echo "Car status : \n";
echo "Model :" . $this->model . "\n";
echo "Make :" . $this->make . "\n\n";
}
function get_speed () {
return $this->speed;
}
}
$car1 = new Car();
$car1->get_status("Vios", "Toyota");
for( $i = 0; $i < 5 ; $i++) {
echo "Accelerating... <br> \n";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
就像之前我说的那样 - 因为你调用类的方式对你所拥有的结构没什么意义,我稍微重写了上面的代码,所以它循环遍历一系列汽车价值:
$car_array = array("Vios", "Toyota");
foreach ($car_array as $car_value) {
$car1 = new Car($car_value);
$car1->get_status();
for( $i = 0; $i < 5 ; $i++) {
echo "Accelerating... <br> \n";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
}
答案 1 :(得分:0)
连接字符串时,必须使用点运算符:
echo "abcd" . "efgh";
答案 2 :(得分:0)
添加如下构造函数:
public function __construct($model = 0, $make = 0, $speed = 0) {
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}