Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Car {
- // properties (attributes) with proper visibility
- public $model;
- public $color;
- public $fuelLevel;
- // Constructor to initialize the car with model and color
- public function __construct($model, $color) {
- $this->model = $model;
- $this->color = $color;
- $this->fuelLevel = 100; // Default fuel level is set to 100
- }
- // Public method to get the model of the car
- public function getModel() {
- return $this->model;
- }
- // Public method to get the color of the car
- public function getColor() {
- return $this->color;
- }
- // Public method to get the fuel level of the car
- public function getFuelLevel() {
- return $this->fuelLevel;
- }
- // Public method to simulate driving, reducing fuel level
- public function drive() {
- // Simulate driving by reducing fuel level
- $this->fuelLevel -= 10;
- if ($this->fuelLevel < 0) {
- $this->fuelLevel = 0; // Ensure fuel level doesn't go below 0
- }
- }
- }
- // Create a new car object
- $myCar = new Car("Toyota", "Blue");// Output the car details
- echo "Model: " . $myCar->getModel() . "<br>";
- echo "Color: " . $myCar->getColor() . "<br>";
- echo "Fuel Level: " . $myCar->getFuelLevel() . "%<br>";
- // Simulate driving the car
- $myCar->drive();
- // Output the updated fuel level after driving
- echo "Updated Fuel Level after driving: " . $myCar->getFuelLevel() . "%";
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement