PHP What is OOP

Object-oriented programming (OOP) is a way of structuring code around self-contained objects that bundle related data and behavior together.

What is object-oriented programming?

Object-oriented programming is a style of writing software in which you model your program as a collection of objects. Each object groups together some data (called properties) and the actions that work on that data (called methods). Instead of scattering related variables and functions across a file, OOP lets you keep them in one place, so a 'User' object knows both what a user is and what a user can do.

PHP started life as a procedural language, where programs are built from a sequence of functions that pass data around. It still fully supports that style, but since PHP 5 the language has offered a mature object model. For anything beyond a small script, OOP tends to produce code that is easier to organize, test, and grow over time.

Procedural versus object-oriented

In procedural code you might store a person's name in a variable and write a separate function that greets them. In object-oriented code, the name and the greeting live together inside one object. The object becomes responsible for its own state, which reduces the chance of unrelated code accidentally changing data it shouldn't touch.

ConceptProceduralObject-oriented
DataLoose variables and arraysProperties inside objects
BehaviorStandalone functionsMethods belonging to a class
ReuseCopy or call functionsInheritance, interfaces, traits
ScaleHarder as code growsEasier to extend and maintain

The four core ideas

  • Encapsulation: keep an object's internal data private and expose only a controlled set of methods to work with it.
  • Abstraction: hide complicated details behind a simple, predictable interface so callers only see what they need.
  • Inheritance: let a new class build on an existing one, reusing and extending its behavior.
  • Polymorphism: allow different classes to respond to the same method call in their own way.

A first taste of OOP in PHP

<?php
class Greeter
{
    public string $name;

    public function greet(): string
    {
        return "Hello, " . $this->name . "!";
    }
}

$g = new Greeter();
$g->name = "Ada";
echo $g->greet(); // Hello, Ada!
?>
Note: You do not have to choose one style for an entire project. Many PHP applications mix procedural helper functions with object-oriented components. OOP simply gives you extra tools for organizing larger, longer-lived code.

Throughout the rest of this section you will build on this foundation: defining classes, creating objects from them, controlling how they are set up and cleaned up, protecting their data, and sharing behavior between them. Each idea introduced here will become concrete as you write real classes.