In this lesson, you will learn advanced Object-Oriented Programming (OOP) concepts in PHP, including inheritance, polymorphism, abstract classes, and interfaces. These concepts are critical for building reusable, scalable, and modular PHP applications.
11.1 Inheritance
What is Inheritance?
- Inheritance allows a class (child class) to inherit properties and methods from another class (parent class).
- Promotes code reuse and helps in extending the functionality of existing classes.
Syntax
Example: Inheritance
Overriding Methods
- A child class can override a method from the parent class to provide a new implementation.
Using parent::
- Use
parent::
to call the parent class’s method inside the child class.
11.2 Polymorphism
What is Polymorphism?
- Polymorphism means “many forms.” It allows objects of different classes to be treated as objects of a common parent class.
- Achieved through method overriding and interfaces.
Example: Polymorphism
11.3 Abstract Classes
What is an Abstract Class?
- An abstract class serves as a blueprint for other classes.
- It cannot be instantiated directly.
- It can have both abstract (unimplemented) and non-abstract (implemented) methods.
Syntax
Example: Abstract Class
11.4 Interfaces
What is an Interface?
- An interface defines a contract that implementing classes must follow.
- All methods in an interface are abstract by default.
- A class can implement multiple interfaces, allowing for multiple inheritances.
Syntax
Example: Interface
Extending Multiple Interfaces
Practical Example: Combining Concepts
Example: Shape Class
Activities and Exercises
- Inheritance:
- Create a
Vehicle
class and aCar
class that extends it. Add methods for starting and stopping the vehicle.
- Create a
- Polymorphism:
- Implement a function that takes a
Shape
object (Rectangle, Circle, etc.) and prints its area.
- Implement a function that takes a
- Abstract Classes:
- Create an abstract class
Payment
with an abstract methodprocessPayment()
. Implement it in classes forCreditCardPayment
andPaypalPayment
.
- Create an abstract class
- Interfaces:
- Create an interface
Logger
with a methodlogMessage()
. Implement the interface in classes forFileLogger
andDatabaseLogger
.
- Create an interface
Assignment
- Create an abstract class
Employee
with:- Properties:
name
,salary
. - Abstract method
calculateBonus()
.
- Properties:
- Implement two child classes:
Manager
with a bonus of 20% of the salary.Developer
with a bonus of 10% of the salary.
- Create a script to calculate and display the bonus for both managers and developers.
Summary
In this lesson, you learned:
- How to use inheritance to extend functionality.
- How polymorphism allows different objects to be treated uniformly.
- How abstract classes and interfaces define reusable blueprints for classes.
These advanced concepts form the backbone of scalable and maintainable PHP applications. Let me know if you need more examples or exercises!
Leave a Reply