31. Why OOP? Concepts and Principles
Object-Oriented Programming (OOP) is a paradigm that structures programs around objects rather than actions and logic. While procedural PHP is fine for small scripts, OOP is mandatory for large, complex, and maintainable applications (like those built with frameworks).
The Core Concepts
1. Classes and Objects
- Class: A blueprint or template for creating objects. (e.g., the concept of a 'Car').
- Object: An instance of a class. (e.g., your specific Toyota, with its color and VIN).
2. Encapsulation
Bundling data (properties) and methods (functions) that operate on the data into a single unit (the object). It also involves restricting direct access to some of the object's components (using access modifiers).
- Goal: Protect data from accidental modification and hide internal implementation details.
3. Inheritance
Allows one class (the child/subclass) to inherit properties and methods from another class (the parent/superclass). This promotes code reuse.
- Example: A 'SportsCar' inherits from the general 'Car' class.
4. Polymorphism
The ability of different objects to respond to the same message (method call) in their own way. 'Poly' means many, 'morph' means form.
- Example: If both a 'Dog' object and a 'Cat' object have a
makeSound()method, the Dog will bark and the Cat will meow.