Advertisement
vvccs

wt_8_basic_oops

Oct 13th, 2024 (edited)
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. <?php
  2. class Car {
  3. // properties (attributes) with proper visibility
  4. public $model;
  5. public $color;
  6. public $fuelLevel;
  7. // Constructor to initialize the car with model and color
  8. public function __construct($model, $color) {
  9. $this->model = $model;
  10. $this->color = $color;
  11. $this->fuelLevel = 100; // Default fuel level is set to 100
  12. }
  13. // Public method to get the model of the car
  14. public function getModel() {
  15. return $this->model;
  16. }
  17. // Public method to get the color of the car
  18. public function getColor() {
  19. return $this->color;
  20. }
  21. // Public method to get the fuel level of the car
  22. public function getFuelLevel() {
  23. return $this->fuelLevel;
  24. }
  25. // Public method to simulate driving, reducing fuel level
  26. public function drive() {
  27. // Simulate driving by reducing fuel level
  28. $this->fuelLevel -= 10;
  29. if ($this->fuelLevel < 0) {
  30. $this->fuelLevel = 0; // Ensure fuel level doesn't go below 0
  31. }
  32. }
  33. }
  34. // Create a new car object
  35. $myCar = new Car("Toyota", "Blue");// Output the car details
  36. echo "Model: " . $myCar->getModel() . "<br>";
  37. echo "Color: " . $myCar->getColor() . "<br>";
  38. echo "Fuel Level: " . $myCar->getFuelLevel() . "%<br>";
  39. // Simulate driving the car
  40. $myCar->drive();
  41. // Output the updated fuel level after driving
  42. echo "Updated Fuel Level after driving: " . $myCar->getFuelLevel() . "%";
  43. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement