PHP OOP Introduction
OOP (Object Oriented Programming) is a way of writing code where you organize it into objects. An object has data (called properties) and actions (called methods), just like things in real life. A car has a color and a brand (data), and it can start or stop (actions).
Sometimes you will see the term OOPs. It means Object Oriented Programming System. PHP supports both procedural and object oriented style, and almost all modern PHP code and frameworks use OOP.
Procedural vs object oriented
| Procedural | Object oriented |
|---|---|
| Code is a list of functions and variables | Code is grouped in classes and objects |
| Data and functions are separate | Data and functions live together in an object |
| Easy for small scripts | Better for big projects, easy to reuse and maintain |
| Same code is often repeated | Code is reused with inheritance and traits |
Why use OOP?
- Reuse: write a class once and create many objects from it.
- Organized code: related data and functions stay together.
- Easy to maintain: a change in one class does not break the whole project.
- Safe data: you can hide the data of an object and give access only through methods.
Important OOP terms
| Term | Meaning |
|---|---|
| Class | A blueprint or template to create objects |
| Object | A real thing created from a class |
| Property | A variable that belongs to a class |
| Method | A function that belongs to a class |
| Constructor | A special method that runs when an object is created |
| Inheritance | A child class gets the properties and methods of a parent class |
| Polymorphism | Different classes can have the same method name but work differently |
| Abstraction | Hide the complex details and show only what is needed |
| Encapsulation | Keep the data private and give access with public methods |
A first look at class and object
<?php
class Greeting {
public function say() {
return "Hello from a PHP object!";
}
}
$obj = new Greeting();
echo $obj->say();
?>
Output:
Tutorials Class - Output Window
Hello from a PHP object!
Here Greeting is the class and $obj is an object made from it. The next chapters explain these in detail.
What next?
- Learn how to write a class: PHP Class.
- Learn how to create and use objects: PHP Objects.
- Practice with OOP interview questions: PHP OOPs Interview Questions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |