PHP / PHP Object-Oriented Programming (OOP)
Implementing Inheritance and Polymorphism
This tutorial will guide you through implementing inheritance and polymorphism in PHP. These are powerful OOP features that allow for efficient, modular, and maintainable code.
Section overview
5 resourcesExplores object-oriented programming concepts in PHP.
Introduction
In this tutorial, our main goal is to learn how to implement inheritance and polymorphism in PHP. Inheritance is a mechanism that allows you to create a new class from an existing class. The new class inherits all the properties and methods of the existing class and can add new ones or modify the inherited ones. Polymorphism is the ability of an object to take on many forms, which allows us to perform a single action in different ways.
By the end of this tutorial, you will have learned:
- What inheritance and polymorphism are;
- How to implement inheritance and polymorphism in PHP.
Prerequisites
Basic understanding of PHP (variables, functions, classes) and familiarity with Object-Oriented Programming (OOP) concepts.
Step-by-Step Guide
Inheritance
In PHP, a class can be defined based on another class using the extends keyword. The class that is being extended is called the parent class, and the class that extends is called the child class.
Here's an example:
class ParentClass {
protected $name;
public function setName($name) {
$this->name = $name;
}
}
class ChildClass extends ParentClass {
public function welcome() {
return "Hello, " . $this->name;
}
}
In this example, the ChildClass extends the ParentClass and inherits the $name property and the setName() method.
Polymorphism
Polymorphism in PHP can be achieved using interfaces. An interface defines a contract for what a class can do, without saying anything about how the class will do it. A class can implement an interface using the implements keyword.
Here's an example:
interface Shape {
public function area();
}
class Circle implements Shape {
protected $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * pow($this->radius, 2);
}
}
class Square implements Shape {
protected $length;
public function __construct($length) {
$this->length = $length;
}
public function area() {
return pow($this->length, 2);
}
}
In this example, Circle and Square are two different classes implementing the same interface Shape, but the area() method is implemented differently in both classes.
Code Examples
Inheritance
Here's an example of how we can use the child class and its inherited method.
$child = new ChildClass();
$child->setName("John");
echo $child->welcome(); // Outputs: Hello, John
Polymorphism
Here's an example of how we can use the polymorphism concept.
$circle = new Circle(3);
echo $circle->area(); // Outputs: 28.274333882308 (which is pi*radius^2)
$square = new Square(4);
echo $square->area(); // Outputs: 16 (which is side_length^2)
In this example, both Circle and Square classes are using the same method name area(), but the output is different based on the implementation.
Summary
In this tutorial, we have learned about inheritance and polymorphism in PHP. Inheritance allows us to create a new class from an existing one, inheriting its properties and methods. Polymorphism allows us to perform a single action in different ways.
Practice Exercises
-
Exercise 1: Create a
Vehicleparent class with aspeedproperty and asetSpeedmethod. Then createCarandBikechild classes that inherit from theVehicleclass. Each child class should have amaximumSpeedmethod that prints a message with the maximum speed. -
Exercise 2: Create an interface
Animalwith a methodmakeSound. Implement this interface in theDogandCatclasses. ThemakeSoundmethod should return "Bark" for theDogclass and "Meow" for theCatclass. -
Exercise 3: Extend the
Animalinterface and add aeatmethod. Implement this method in both theDogandCatclasses.
Solutions
- Solution for Exercise 1:
class Vehicle {
protected $speed;
public function setSpeed($speed) {
$this->speed = $speed;
}
}
class Car extends Vehicle {
public function maximumSpeed() {
return "The maximum speed of the car is " . $this->speed;
}
}
class Bike extends Vehicle {
public function maximumSpeed() {
return "The maximum speed of the bike is " . $this->speed;
}
}
- Solution for Exercise 2:
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
return "Bark";
}
}
class Cat implements Animal {
public function makeSound() {
return "Meow";
}
}
- Solution for Exercise 3:
interface Animal {
public function makeSound();
public function eat();
}
class Dog implements Animal {
public function makeSound() {
return "Bark";
}
public function eat() {
return "The dog is eating.";
}
}
class Cat implements Animal {
public function makeSound() {
return "Meow";
}
public function eat() {
return "The cat is eating.";
}
}
Keep practicing and implementing these concepts in your own projects to get a good grasp of them. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article