0
0
PHPprogramming~30 mins

Type hinting with parent classes in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Type hinting with parent classes
📖 Scenario: You are building a simple system to manage different types of vehicles. Each vehicle has a method to display its type. You want to use type hinting with a parent class to ensure your functions accept any vehicle type.
🎯 Goal: Create a parent class Vehicle and two child classes Car and Bike. Then write a function that accepts a Vehicle type and calls its method to display the vehicle type.
📋 What You'll Learn
Create a parent class called Vehicle with a method getType().
Create two child classes Car and Bike that extend Vehicle and override getType().
Write a function printVehicleType that accepts a parameter type hinted as Vehicle.
Call getType() inside printVehicleType and print the result.
💡 Why This Matters
🌍 Real World
Type hinting with parent classes helps write flexible code that works with many related objects, like different vehicle types in a transport app.
💼 Career
Understanding inheritance and type hinting is essential for writing clean, maintainable PHP code in many software development jobs.
Progress0 / 4 steps
1
Create the parent class Vehicle
Create a class called Vehicle with a public method getType() that returns the string 'Generic Vehicle'.
PHP
Need a hint?

Use class Vehicle {} and inside it define public function getType(): string that returns 'Generic Vehicle'.

2
Create child classes Car and Bike
Create two classes called Car and Bike that extend Vehicle. Override the getType() method in each to return 'Car' and 'Bike' respectively.
PHP
Need a hint?

Use class Car extends Vehicle and override getType() to return 'Car'. Do the same for Bike returning 'Bike'.

3
Write function with type hinting for Vehicle
Write a function called printVehicleType that accepts one parameter $vehicle type hinted as Vehicle. Inside the function, call $vehicle->getType() and print the returned string.
PHP
Need a hint?

Define function printVehicleType(Vehicle $vehicle): void and inside use echo $vehicle->getType() to print the type.

4
Call function with Car and Bike objects and print output
Create an object $car of class Car and an object $bike of class Bike. Call printVehicleType with $car and then with $bike to print their types.
PHP
Need a hint?

Create objects with new Car() and new Bike(). Then call printVehicleType($car) and printVehicleType($bike).