PHP Object-Oriented Programming
PHP Object-Oriented Programming (OOP)
In PHP, OOP stands for Object-Oriented Programming.
PHP OOP is about organizing code into classes and objects that have properties and methods.
PHP OOP is ideal for building scalable, reusable, and maintainable code.
Traditional procedural programming follows a step-by-step approach and will execute the commands sequentially, while object-oriented programming is about creating classes and objects, and decide how they will interact.
Object-oriented programming has several advantages over procedural programming:
- OOP is faster and easier to execute
- OOP provides a clear structure for the program
- OOP helps to keep the code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
- OOP makes it possible to create full reusable applications with less code and shorter development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.
PHP OOP helps create modular, reusable, and maintainable code by using:
- Classes and Objects - A class is a template for objects, and an object is an individual instance of a class
- Encapsulation - Allows developers to control access to an object's internal state by using access modifiers (public, protected, private)
- Inheritance - Allows a new class to inherit properties and methods from an existing class
- Abstraction - A class that cannot be instantiated on its own and is used as a blueprint for other classes
- Interfaces - Defines a set of methods that implementing classes must adhere to
PHP - What are Classes and Objects?
Classes and objects are two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
So, a class is a template for objects, and an object is an individual instance of a class.
When an object is created, it will inherit all the properties and methods from the class, but each object will have different values for the properties.
Look at the next chapters to learn more about OOP.