W3docs

Understanding Object-Oriented Programming (OOP) in PHP

Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and code that operates on that

Object-Oriented Programming (OOP) is a programming paradigm built around the concept of "objects", which bundle together data (properties) and behavior (methods) that operates on that data. Instead of scattering related variables and functions across your script, OOP lets you group them into self-contained units that model the things your application deals with — a User, an Order, a Product.

This chapter covers the two foundations of OOP in PHP — classes and objects — and then walks through the three ideas you will use them with every day: encapsulation, inheritance, and polymorphism. By the end you will be able to read and write PHP classes confidently and know which feature solves which problem.

What are Classes and Objects in PHP OOP?

A class is a blueprint. It describes what data an object holds and what it can do, but it is not a thing in itself — much like an architectural plan is not a house. An object is a concrete instance built from that blueprint, created with the new keyword. You can create many objects from one class, each with its own data.

TermWhat it isExample
ClassThe blueprint (definition)class User { ... }
ObjectA live instance of a class$alice = new User(...)
PropertyA variable that belongs to an object$this->email
MethodA function that belongs to a classgetEmail()

A useful way to remember it: the class is the cookie cutter, the objects are the cookies. Classes and objects are the building blocks of OOP in PHP.

Defining Classes in PHP

Classes in PHP are defined using the class keyword, followed by the name of the class. The properties and methods of a class are defined inside the class definition, within curly braces ({}). Here is an example of a class definition in PHP:

Example of a class definition in PHP

class User {
    public $username;
    public $email;
    public function __construct($username, $email) {
        $this->username = $username;
        $this->email = $email;
    }
    public function getUsername() {
        return $this->username;
    }
    public function getEmail() {
        return $this->email;
    }
}

In this example, the User class has two properties, $username and $email, and two methods, getUsername() and getEmail(). The __construct method is a special constructor method in PHP: it runs automatically the moment an object is created, which makes it the natural place to set up an object's initial state. Inside any method, $this refers to the current object, so $this->username means "this object's username property". To learn more about constructors and the matching cleanup method, see PHP Constructor and PHP Destructor.

Creating Objects from Classes

To create an object from a class, use the new keyword, followed by the name of the class. Here is an example of how to create an object from the User class:

PHP create an object from a class by using new keyword

$user = new User("John Doe", "[email protected]");

This creates a new User object and stores it in the variable $user. You can access the properties and methods of the object using the arrow operator (->). Here is an example of how to access the properties and methods of the $user object:

PHP access the properties and methods of the object using the arrow operator

echo $user->username; // Outputs: "John Doe"
echo $user->email; // Outputs: "[email protected]"
echo $user->getUsername(); // Outputs: "John Doe"
echo $user->getEmail(); // Outputs: "[email protected]"

Encapsulation: Controlling Access to Data

In the examples above, every property is declared public, which means any code can read or change it directly ($user->email = "..."). That is convenient but risky — it lets the rest of your program put an object into an invalid state. Encapsulation is the practice of hiding an object's internals and exposing a controlled interface instead.

PHP provides three visibility modifiers for properties and methods:

ModifierAccessible fromUse it when
publicAnywhereThe member is part of the object's official interface.
protectedThe class and its subclassesSubclasses need it, but outside code should not.
privateOnly the same classThe member is an internal detail.

By making a property private and exposing methods to read or change it, you keep validation in one place:

<?php

class BankAccount
{
    private $balance = 0;

    public function deposit($amount)
    {
        if ($amount <= 0) {
            throw new InvalidArgumentException("Deposit must be positive.");
        }
        $this->balance += $amount;
    }

    public function getBalance()
    {
        return $this->balance;
    }
}

$account = new BankAccount();
$account->deposit(100);
$account->deposit(50);
echo $account->getBalance(); // Outputs: 150

Because $balance is private, no outside code can set it to a negative number directly — every change must go through deposit(), where the rule lives. For a deeper look at the three keywords, read PHP Access Modifiers.

Inheritance in PHP OOP

Inheritance is a feature of OOP that allows classes to inherit properties and methods from parent classes. This allows developers to create new classes that are based on existing classes, without having to write all the code again. In PHP, inheritance is defined using the extends keyword. Here is an example of inheritance in PHP:

PHP example of inheritance is a feature of OOP that allows classes

class Admin extends User {
    public $permissions;
    public function __construct($username, $email, $permissions) {
        parent::__construct($username, $email);
        $this->permissions = $permissions;
    }
    public function getPermissions() {
       return $this->permissions;
   }
}

In this example, the Admin class extends the User class and inherits its properties and methods. The Admin class also has its own property, $permissions, and method, getPermissions(). The parent:: keyword is used to call the parent class's __construct method, allowing the Admin class to reuse the logic from the User class instead of duplicating it. A class can extend only one parent in PHP. For the full picture, see PHP Inheritance.

Polymorphism in PHP OOP

Polymorphism is a feature of OOP that allows objects of different classes to be treated as objects of the same class. This allows developers to write generic code that can work with objects of different classes, as long as they have the same methods. In PHP, polymorphism is achieved by defining common methods in parent classes and implementing them in child classes. Here is an example of polymorphism in PHP:

Example of polymorphism in PHP

<?php

class User
{
    public $username;
    public $email;

    public function __construct($username, $email)
    {
        $this->username = $username;
        $this->email = $email;
    }
    public function getUsername()
    {
        return $this->username;
    }
    public function getEmail()
    {
        return $this->email;
    }

    public function showInfo()
    {
        echo "Username: " . $this->username . "\n";
        echo "Email: " . $this->email . "\n";
    }
}

class Admin extends User
{
    public $permissions;
    public function __construct($username, $email, $permissions)
    {
        parent::__construct($username, $email);
        $this->permissions = $permissions;
    }
    public function getPermissions()
    {
        return $this->permissions;
    }

    public function showInfo()
    {
        parent::showInfo();
        echo "Permissions: " . $this->permissions . "\n";
    }
}

$user = new User("John Doe", "[email protected]");
$admin = new Admin("Jane Doe", "[email protected]", ["read", "write", "delete"]);

$users = [$user, $admin];

foreach ($users as $user) {
    $user->showInfo();
}

In this example, the User class and the Admin class both have a showInfo() method. When the showInfo() method is called on an object, the correct implementation of the method is called, based on the type of the object. This allows the foreach loop to treat the $user and $admin objects as objects of the same type, even though they are instances of different classes.

Conclusion

Object-Oriented Programming (OOP) is a powerful paradigm widely used in PHP for building scalable, maintainable web applications. Classes and objects are the building blocks; encapsulation, inheritance, and polymorphism are the features that let you write efficient, reusable code. Master these and the rest of PHP's object model falls into place.

Where to go next:

Practice

Practice
In PHP, what are the characteristics and functionalities of Objects and Classes?
In PHP, what are the characteristics and functionalities of Objects and Classes?
Was this page helpful?