PHP What is OOP?
OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on data, while object-oriented programming is about creating objects that contain both data and functions.
1. The Concept of Classes and Objects
Think of a Class as a blueprint (like a drawing of a car) and an Object as the actual thing built from that blueprint (like a specific Toyota or Ford car).
- Class: A template for objects. It defines properties (variables) and methods (functions).
- Object: An individual instance of a class. When the individual objects are created, they inherit all the properties and behaviors from the class.
2. Why Use OOP?
OOP is faster and easier to execute. It provides a clear structure for programs and helps to keep the PHP code DRY ("Don't Repeat Yourself").
- Modularity: Code can be divided into independent modules.
- Reusability: You can reuse a class in different parts of your application.
- Maintenance: It is easier to maintain and modify existing code since new objects can be created with small changes to existing ones.
3. A Simple Class Example
To define a class, use the class keyword followed by the name of the class.
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
// Create an Object
$apple = new Fruit();
$apple->set_name('Apple');
echo $apple->get_name();
?>
4. The $this Keyword
The $this keyword refers to the current object. It is only available inside methods and is used to access the properties or methods of the class from within.
5. The Four Pillars of OOP
To master PHP OOP, you will eventually learn these four main concepts:
- Inheritance: A class can derive properties and methods from another class.
- Encapsulation: Wrapping data and code into a single unit and restricting access.
- Abstraction: Hiding complex implementation details and showing only the necessary features.
- Polymorphism: Allowing different classes to be treated as instances of the same parent class through the same interface.
Tip: In a large project, OOP makes your code much more organized. Instead of having one giant file with hundreds of functions, you have many small, manageable classes.