PHP PHP OOPS - Classs Object

PHP – Inheritance in Action

What is Inheritance?
Inheritance allows a class (child class) to inherit the properties and methods of another class (parent class). The child class can also define its own properties and methods, extending the functionality of the parent class.

The extends keyword is used to define inheritance.

<?php
// Parent class
class Vehicle {
  public $brand;
  public $color;

  public function __construct($brand, $color) {
    $this->brand = $brand;
    $this->color = $color;
  }

  public function description() {
    echo "This is a {$this->color} {$this->brand} vehicle.";
  }
}

// Child class: Car
class Car extends Vehicle {
  public $seats;

  public function __construct($brand, $color, $seats) {
    parent::__construct($brand, $color); // Call parent constructor
    $this->seats = $seats;
  }

  public function description() {
    echo "This is a {$this->color} {$this->brand} car with {$this->seats} seats.";
  }
}

// Child class: Bike
class Bike extends Vehicle {
  public $type;

  public function __construct($brand, $color, $type) {
    parent::__construct($brand, $color); // Call parent constructor
    $this->type = $type;
  }

  public function description() {
    echo "This is a {$this->color} {$this->brand} bike, which is a {$this->type} bike.";
  }
}

// Test the classes
$car = new Car("Toyota", "red", 4);
$car->description(); // Outputs: This is a red Toyota car with 4 seats.

echo "<br>";

$bike = new Bike("Yamaha", "blue", "sports");
$bike->description(); // Outputs: This is a blue Yamaha bike, which is a sports bike.
?>

Key Concepts Illustrated
Inheritance:

Both Car and Bike inherit from the Vehicle class.
The common properties (brand, color) and method (description()) are inherited.
Overriding Methods:

The description() method is overridden in the child classes to provide specific details for cars and bikes.
Using parent::__construct():

The parent constructor is called in the child class to initialize shared properties.

Example 2: Preventing Inheritance and Overriding
Prevent Class Inheritance:
Use the final keyword to prevent a class from being extended.

<?php
final class Vehicle {
  // Prevents any class from inheriting
}

// Results in error
class Car extends Vehicle {
  // Some code
}
?>

Prevent Method Overriding:
Use the final keyword to prevent a method from being overridden

<?php
class Vehicle {
  final public function description() {
    echo "This is a vehicle.";
  }
}

class Car extends Vehicle {
  // Results in error
  public function description() {
    echo "This is a car.";
  }
}
?>

Summary
Inheritance is a powerful feature in PHP that allows you to reuse code and extend functionality. By using access modifiers and the final keyword appropriately, you can control how classes and methods behave in your applications.

Leave a Reply

Your email address will not be published. Required fields are marked *