<?php
// Parent class
class Vehicle {
public $brand;
public $model;
// Constructor
public function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
}
// Method in parent class
public function start() {
echo "The vehicle is starting.\n";
}
}
// Child class inheriting from the Vehicle class
class Car extends Vehicle {
public $doors;
// Constructor in child class
public function __construct($brand, $model, $doors) {
// Call parent class constructor to initialize properties
parent::__construct($brand, $model);
$this->doors = $doors;
}
// Method in child class
public function honk() {
echo "The car is honking.\n";
}
// Overriding the parent method
public function start() {
echo "The car is starting.\n";
}
}
// Creating an instance of the Car class
$car = new Car("Toyota", "Corolla", 4);
// Accessing inherited properties
echo "Brand: " . $car->brand . "\n"; // Outputs: Brand: Toyota
echo "Model: " . $car->model . "\n"; // Outputs: Model: Corolla
echo "Doors: " . $car->doors . "\n"; // Outputs: Doors: 4
// Calling methods
$car->start(); // Outputs: The car is starting.
$car->honk(); // Outputs: The car is honking.
?>
No hay comentarios:
Publicar un comentario