PHP class vehicle: Display vehicle details
5. Vehicle Class
Write a PHP class called 'Vehicle' with properties like 'brand', 'model', and 'year'. Implement a method to display the vehicle details.
Sample Solution:
PHP Code :
<?php
class Vehicle {
private $brand;
private $model;
private $year;
public function __construct($brand, $model, $year) {
$this->brand = $brand;
$this->model = $model;
$this->year = $year;
}
public function displayDetails() {
echo "Brand: " . $this->brand . "</br>";
echo "Model: " . $this->model . "</br>";
echo "Year: " . $this->year . "</br>";
}
}
$car = new Vehicle("Ford", "F-150", 2020);
$car->displayDetails();
?>
Sample Output:
Brand: Ford Model: F-150 Year: 2020
Explanation:
In the above exercise -
- The "Vehicle" class has three private properties: $brand, $model, and $year, which represent the brand, model, and manufacturing year of the vehicle.
- The constructor method "__construct()" is used to initialize the values of the properties when creating a new instance of the Vehicle class.
- The "displayDetails()" method displays vehicle details by echoing the properties values.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP class that validates the year property to ensure it is a four-digit number before setting the vehicle details.
- Write a PHP program that extends the Vehicle class to include a method for displaying detailed specifications in a formatted string.
- Write a PHP script to compare two Vehicle objects based on their year and brand, then output the more recent one.
- Write a PHP program that uses the Vehicle class to simulate a fleet inventory and generates a report of all vehicles.
Go to:
PREV : Resizable Interface with Square Class.
NEXT : Library System Class Hierarchy.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.