Lots of issues with your code. But at least this cleaned up version should work without the script dying completely. Here is a breakdown of what I did:
- Set the variables that were set as
var
to public
since that is the preferred method of setting variables.
- In
function Car
, I set default values for $model
, $make
& $speed
so if they are not passed—like in your example—there is at least a default value to act on.
- Your
echo
lines in get_status
did not have the .
for concatenation so they were not properly concatenating the strings.
- Then you setting
$this-> make
and $this-> model
with empty spaces is syntactically incorrect. So set those to $this->make
and $this->model
.
- Then when you are calling the class, you set this
"Current speed : accelerate(5) km/h <br>";
which is syntactically incorrect as well. So set that to echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
so it can actually echo values.
But that said, unclear on what the output is for this code. The logic is a bit of a mess. But at least it’s not completely dying like it did before!
And here is the cleaned up code:
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 :
";
echo "Model :" . $this->model . "
";
echo "Make :" . $this->make . "
";
}
function get_speed () {
return $this->speed;
}
}
$car1 = new Car();
$car1->get_status("Vios", "Toyota");
for( $i = 0; $i < 5 ; $i++) {
echo "Accelerating... <br>
";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
And—like I said before—since the way you are calling the class makes little sense to the structure you have, I slightly reworked the code above so it loops through an array of car values like this:
$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>
";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
}