PHP OOP

This article explains PHP object-oriented programming in detail, including classes, objects, constructors, destructors, access modifiers, inheritance, constants, abstract classes, interfaces, traits, static methods, namespaces, and iterables.

Jun 10, 2026
PHP OOP

PHP OOP: Classes, Objects, Inheritance, Interfaces, Traits and More

Object-oriented programming, also known as OOP, is one of the most important programming styles used in modern PHP development. It helps developers organize code into reusable structures and makes applications easier to maintain as they grow.

In PHP, OOP is used heavily in frameworks such as Laravel, Symfony, and many other professional backend systems. Understanding OOP is an important step before working deeply with modern PHP applications.

This article explains the main PHP OOP topics shown in the learning path: what OOP is, classes and objects, constructors, destructors, access modifiers, inheritance, constants, abstract classes, interfaces, traits, static methods, static properties, namespaces, and iterables.

PHP What is OOP

OOP stands for Object-Oriented Programming. It is a programming approach that organizes code around objects instead of only functions and variables.

An object can represent something in the application, such as a user, product, post, invoice, order, message, or file. Each object can have data and behavior.

In OOP, data is usually stored in properties, while behavior is usually written as methods.

For example, a user object may have properties such as name, email, and role. It may also have methods such as login, logout, updateProfile, or hasPermission.

OOP is useful because it helps developers:

  • Organize code into clear structures.

  • Reuse logic across the application.

  • Reduce repeated code.

  • Model real application concepts more clearly.

  • Make large projects easier to maintain.

  • Work better with modern PHP frameworks.

PHP Classes/Objects

A class is a blueprint for creating objects. It defines the properties and methods that an object can have.

An object is an instance of a class. This means that the class describes the structure, while the object is the actual usable version created from that structure.

<?php
class User {
    public $name;
    public $email;

    public function sayHello() {
        return "Hello, " . $this->name;
    }
}

$user = new User();

$user->name = "Adnan";
$user->email = "adnan@example.com";

echo $user->sayHello();
?>

In this example, User is the class, and $user is an object created from that class.

The $this keyword refers to the current object. It is used inside the class to access the object's properties and methods.

Classes and objects are the foundation of PHP OOP. Most advanced OOP concepts are built on top of them.

PHP Constructor

A constructor is a special method that runs automatically when a new object is created. In PHP, the constructor method is named __construct().

Constructors are commonly used to set initial values for object properties.

<?php
class User {
    public $name;
    public $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }

    public function getInfo() {
        return $this->name . " - " . $this->email;
    }
}

$user = new User("Adnan", "adnan@example.com");

echo $user->getInfo();
?>

Instead of creating the object first and then manually setting each property, the constructor allows values to be passed directly when the object is created.

Constructors are useful for dependency injection, initial configuration, required values, and preparing an object before it is used.

PHP Destructor

A destructor is a special method that runs automatically when an object is destroyed or when the script finishes. In PHP, the destructor method is named __destruct().

Destructors can be used for cleanup tasks, such as closing resources, writing final logs, or releasing temporary data.

<?php
class Logger {
    public function __construct() {
        echo "Logger started.";
    }

    public function __destruct() {
        echo "Logger finished.";
    }
}

$logger = new Logger();
?>

In many modern PHP applications, destructors are not used as often as constructors, but they are still part of the OOP lifecycle.

Developers should use destructors carefully and avoid putting critical business logic inside them, because their execution timing can depend on how the script ends.

PHP Access Modifiers

Access modifiers control where properties and methods can be accessed from. PHP provides three main access modifiers: public, protected, and private.

  • public: can be accessed from anywhere.

  • protected: can be accessed inside the class and child classes.

  • private: can be accessed only inside the same class.

<?php
class User {
    public $name;
    protected $role;
    private $password;

    public function setPassword($password) {
        $this->password = $password;
    }

    public function getPassword() {
        return $this->password;
    }
}

$user = new User();

$user->name = "Adnan";
$user->setPassword("secret");
?>

Access modifiers are important because they protect internal data and control how other parts of the application interact with an object.

In professional PHP development, properties are often kept private or protected, while public methods are used to control access to them. This is called encapsulation.

PHP Inheritance

Inheritance allows one class to reuse properties and methods from another class. The parent class contains shared logic, while the child class can extend or customize that logic.

In PHP, inheritance is created using the extends keyword.

<?php
class Person {
    public $name;

    public function sayHello() {
        return "Hello, " . $this->name;
    }
}

class Student extends Person {
    public $grade;

    public function study() {
        return $this->name . " is studying.";
    }
}

$student = new Student();
$student->name = "Adnan";

echo $student->sayHello();
echo $student->study();
?>

In this example, the Student class inherits from the Person class. This means Student can use the properties and methods defined in Person.

Inheritance is useful when multiple classes share common behavior. However, developers should avoid overusing inheritance because it can make code harder to maintain if the class hierarchy becomes too complex.

PHP Constants

Class constants are fixed values that belong to a class. They are useful for values that should not change, such as roles, statuses, types, limits, and configuration-like values.

Class constants are defined using the const keyword.

<?php
class UserRole {
    const ADMIN = "admin";
    const EDITOR = "editor";
    const USER = "user";
}

echo UserRole::ADMIN;
?>

Class constants are accessed using the scope resolution operator ::.

Inside the same class, constants can be accessed using self::.

<?php
class Status {
    const ACTIVE = "active";

    public function getActiveStatus() {
        return self::ACTIVE;
    }
}
?>

Constants help avoid repeated hard-coded strings and make code cleaner and safer.

PHP Abstract Classes

An abstract class is a class that cannot be created directly as an object. It is designed to be extended by other classes.

Abstract classes can contain normal methods and abstract methods. An abstract method has no body in the abstract class and must be implemented by the child class.

<?php
abstract class PaymentGateway {
    abstract public function pay($amount);

    public function currency() {
        return "USD";
    }
}

class StripePayment extends PaymentGateway {
    public function pay($amount) {
        return "Paid " . $amount . " using Stripe.";
    }
}

$payment = new StripePayment();

echo $payment->pay(100);
echo $payment->currency();
?>

Abstract classes are useful when you want to define a shared structure while still forcing child classes to implement specific behavior.

For example, different payment gateways may share some common methods, but each gateway may need its own implementation for payment processing.

PHP Interfaces

An interface defines a contract that classes must follow. It contains method declarations without method bodies.

When a class implements an interface, it must provide the required methods defined by that interface.

<?php
interface Notifier {
    public function send($message);
}

class EmailNotifier implements Notifier {
    public function send($message) {
        return "Sending email: " . $message;
    }
}

class SmsNotifier implements Notifier {
    public function send($message) {
        return "Sending SMS: " . $message;
    }
}
?>

Interfaces are useful when different classes should follow the same structure but implement the logic differently.

For example, email notifications, SMS notifications, and push notifications can all implement the same Notifier interface while sending messages in different ways.

Interfaces are very important in modern PHP development because they support flexible, testable, and loosely coupled code.

PHP Traits

Traits allow developers to reuse methods across multiple classes without using inheritance. A trait is like a reusable group of methods that can be inserted into a class.

Traits are defined using the trait keyword and used inside a class with the use keyword.

<?php
trait HasSlug {
    public function generateSlug($title) {
        return strtolower(str_replace(" ", "-", $title));
    }
}

class Post {
    use HasSlug;
}

$post = new Post();

echo $post->generateSlug("Learning PHP OOP");
?>

Traits are useful when different classes need the same helper behavior but do not naturally belong to the same inheritance hierarchy.

For example, multiple models may need slug generation, logging, formatting, or shared utility methods.

Traits should be used carefully. If a trait becomes too large or contains too much unrelated logic, it can make code harder to understand.

PHP Static Methods

A static method belongs to the class itself, not to a specific object. This means you can call a static method without creating an object from the class.

Static methods are defined using the static keyword.

<?php
class MathHelper {
    public static function add($a, $b) {
        return $a + $b;
    }
}

echo MathHelper::add(5, 10);
?>

Static methods are accessed using the scope resolution operator ::.

They are often used for helper methods, utility classes, simple formatters, and operations that do not need object state.

Inside a static method, you cannot use $this because there is no object instance. Instead, static methods can access static properties or other static methods using self::.

PHP Static Properties

A static property belongs to the class itself instead of a specific object. This means the value is shared across the class rather than stored separately in each object instance.

<?php
class Counter {
    public static $count = 0;

    public function __construct() {
        self::$count++;
    }
}

new Counter();
new Counter();
new Counter();

echo Counter::$count;
?>

In this example, every time a new object is created, the static property $count increases. The value is shared at the class level.

Static properties can be useful for counters, shared configuration, cached values, or class-level state.

However, static state should be used carefully in large applications because it can make testing and debugging more difficult if the state changes unexpectedly.

PHP Namespaces

Namespaces help organize classes, interfaces, traits, and functions into logical groups. They also prevent naming conflicts between classes that may have the same name.

In a large application, many classes may have common names such as User, Controller, Service, Request, or Response. Namespaces allow these names to exist in different parts of the application without conflict.

<?php
namespace App\Models;

class User {
    public function getName() {
        return "Adnan";
    }
}
?>

A class from a namespace can be imported using the use keyword.

<?php
use App\Models\User;

$user = new User();

echo $user->getName();
?>

Namespaces are essential in modern PHP projects. Frameworks such as Laravel and Symfony use namespaces to organize controllers, models, services, middleware, requests, jobs, and many other classes.

PHP Iterables

An iterable is a value that can be looped over using foreach. In PHP, arrays are iterable, and objects can also be iterable if they implement the correct interfaces.

The iterable type can be used as a function parameter type to accept arrays or objects that can be looped through.

<?php
function printItems(iterable $items) {
    foreach ($items as $item) {
        echo $item;
    }
}

printItems(["PHP", "Laravel", "Symfony"]);
?>

Iterables are useful when a function should work with any list-like data structure, not only normal arrays.

PHP also supports generators, which can return iterable values using the yield keyword.

<?php
function numbers() {
    yield 1;
    yield 2;
    yield 3;
}

foreach (numbers() as $number) {
    echo $number;
}
?>

Generators are useful when working with large data because they can produce values one by one without loading everything into memory at once.

How PHP OOP Concepts Work Together

In real PHP applications, these OOP concepts are often used together. A class may have private properties, a constructor, constants, methods, and a namespace. It may implement an interface, use a trait, extend an abstract class, and return iterable data.

The following example combines several OOP concepts in a simple structure.

<?php
namespace App\Services;

interface ReportGenerator {
    public function generate(): iterable;
}

trait HasTimestamp {
    public function currentTime() {
        return date("Y-m-d H:i:s");
    }
}

abstract class BaseReport {
    const FORMAT = "text";

    protected $title;

    public function __construct($title) {
        $this->title = $title;
    }

    abstract public function generate(): iterable;
}

class SalesReport extends BaseReport implements ReportGenerator {
    use HasTimestamp;

    public static $count = 0;

    public function __construct($title) {
        parent::__construct($title);
        self::$count++;
    }

    public function generate(): iterable {
        yield $this->title;
        yield "Generated at: " . $this->currentTime();
        yield "Format: " . self::FORMAT;
    }
}

$report = new SalesReport("Monthly Sales Report");

foreach ($report->generate() as $line) {
    echo $line;
}
?>

This example uses namespace, interface, trait, abstract class, class constant, constructor, static property, inheritance, and iterable output. It shows how OOP concepts can work together to build organized code.

Why OOP Matters in Modern PHP

Modern PHP development depends heavily on OOP. Frameworks, packages, libraries, and professional applications are usually organized around classes, interfaces, services, controllers, models, and reusable objects.

In Laravel, for example, controllers are classes, models are classes, requests are classes, jobs are classes, middleware are classes, and services are often written as classes. Understanding OOP makes it much easier to understand how the framework works.

OOP also supports better testing and cleaner architecture. When code is organized into clear objects and contracts, it becomes easier to replace parts of the application, write unit tests, and maintain the project over time.

Conclusion

PHP object-oriented programming is a key skill for building modern and professional PHP applications. Concepts such as classes, objects, constructors, destructors, access modifiers, inheritance, constants, abstract classes, interfaces, traits, static methods, static properties, namespaces, and iterables help developers write cleaner and more reusable code.

OOP may feel complex at first, but each concept becomes easier when practiced with simple examples. Start with classes and objects, then gradually move to constructors, access modifiers, inheritance, interfaces, traits, and namespaces.

After understanding PHP OOP, the next step is to apply these concepts in real projects and frameworks such as Laravel, where OOP is used in almost every part of the application.