Example of Object-Oriented Programming (OOP) in PHP
In this example, we'll create a Car
class with properties and methods to demonstrate the basic concepts of OOP, such as encapsulation, inheritance, and polymorphism.
In this example:
Encapsulation: The class encapsulates the data (brand, model, year) and the behavior (the
getCarInfo
method) within a single unit, providing a clear interface for the outside world.Constructor: The
__construct
method is a special method that is automatically called when an object is created. It initializes the object's properties with the values passed to the constructor.Inheritance: Although not demonstrated in this basic example, PHP supports inheritance, allowing you to create subclasses that inherit properties and methods from a parent class.
This example illustrates the fundamental principles of OOP in PHP, including creating classes, defining properties and methods, and creating objects of the class.
Comments
Post a Comment