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

ProceduralObject oriented
Code is a list of functions and variablesCode is grouped in classes and objects
Data and functions are separateData and functions live together in an object
Easy for small scriptsBetter for big projects, easy to reuse and maintain
Same code is often repeatedCode 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

TermMeaning
ClassA blueprint or template to create objects
ObjectA real thing created from a class
PropertyA variable that belongs to a class
MethodA function that belongs to a class
ConstructorA special method that runs when an object is created
InheritanceA child class gets the properties and methods of a parent class
PolymorphismDifferent classes can have the same method name but work differently
AbstractionHide the complex details and show only what is needed
EncapsulationKeep 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?


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?