0
0
PHPprogramming~30 mins

Constructor inheritance in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructor inheritance
📖 Scenario: Imagine you are creating a simple system to manage different types of vehicles. Each vehicle has a brand and a model. Cars are a special type of vehicle that also have a number of doors.
🎯 Goal: You will create a base class Vehicle with a constructor to set brand and model. Then create a subclass Car that inherits from Vehicle and adds the number of doors. You will use constructor inheritance to reuse the base class constructor.
📋 What You'll Learn
Create a class Vehicle with a constructor that takes $brand and $model and sets them as properties.
Create a subclass Car that extends Vehicle.
In Car, create a constructor that takes $brand, $model, and $doors.
Use parent::__construct($brand, $model) inside Car constructor to call the base constructor.
Add a property $doors in Car and set it in the constructor.
Create an instance of Car with brand 'Toyota', model 'Corolla', and 4 doors.
Print the brand, model, and doors of the car.
💡 Why This Matters
🌍 Real World
Constructor inheritance is used in many real-world PHP applications to reuse code and organize related classes efficiently, such as in vehicle management systems, user roles, or product categories.
💼 Career
Understanding constructor inheritance is important for PHP developers working on object-oriented projects, frameworks, or any codebase that uses class hierarchies.
Progress0 / 4 steps
1
Create the base class Vehicle
Create a class called Vehicle with a constructor that takes parameters $brand and $model. Inside the constructor, set these parameters to properties $this->brand and $this->model.
PHP
Need a hint?

Use class Vehicle { ... } and inside it define public function __construct($brand, $model).

2
Create subclass Car with constructor
Create a class called Car that extends Vehicle. Add a constructor that takes $brand, $model, and $doors. Inside the constructor, call parent::__construct($brand, $model) to reuse the base constructor. Also set $this->doors to $doors.
PHP
Need a hint?

Use class Car extends Vehicle and inside the constructor call parent::__construct($brand, $model).

3
Create an instance of Car
Create a variable called $myCar and set it to a new Car object with brand 'Toyota', model 'Corolla', and 4 doors.
PHP
Need a hint?

Use $myCar = new Car('Toyota', 'Corolla', 4); to create the object.

4
Print the car details
Print the brand, model, and number of doors of $myCar using echo. Format the output exactly as: Brand: Toyota, Model: Corolla, Doors: 4
PHP
Need a hint?

Use echo "Brand: {$myCar->brand}, Model: {$myCar->model}, Doors: {$myCar->doors}"; to print the details.