PHP OOP Tutorial: Object-Oriented Programming for Beginners (2026)

By Lyndon Bermoy

Updated on:

PHP OOP Tutorial: Object-Oriented Programming for Beginners (2026)

Object-oriented programming (OOP) is the paradigm that modern PHP frameworks are built on. You cannot use Laravel, Symfony, or any professional PHP codebase without understanding classes, objects, inheritance, and interfaces. This tutorial covers PHP OOP from the beginning with practical examples you can run immediately.

Why OOP Matters in PHP

Procedural PHP — writing functions and calling them sequentially — works for small scripts. As applications grow, procedural code becomes difficult to organize, reuse, and maintain. OOP solves this by bundling related data and behavior into objects, making code modular, reusable, and easier to understand.

Every Laravel model, controller, middleware, and service is a class. Understanding OOP is the prerequisite for using any of these effectively.

Classes and Objects

A class is a blueprint — it defines what properties (data) and methods (behavior) objects of that type will have. An object is an instance of a class — the actual thing created from the blueprint.

<?php
// Define a class
class User {
    // Properties — the data a User holds
    public string $name;
    public string $email;
    private string $password;

    // Constructor — runs when you create a new User
    public function __construct(string $name, string $email, string $password) {
        $this->name     = $name;
        $this->email    = $email;
        $this->password = password_hash($password, PASSWORD_BCRYPT);
    }

    // Method — behavior a User can perform
    public function greet(): string {
        return "Hello, I am {$this->name}!";
    }

    public function verifyPassword(string $input): bool {
        return password_verify($input, $this->password);
    }
}

// Create objects (instances) from the class
$user1 = new User('Lyndon', 'lyndon@example.com', 'secret123');
$user2 = new User('Maria', 'maria@example.com', 'pass456');

echo $user1->greet();              // Hello, I am Lyndon!
echo $user2->name;                 // Maria
var_dump($user1->verifyPassword('secret123')); // bool(true)

Access Modifiers

Access modifiers control who can read or modify a property or call a method:

  • public — accessible from anywhere (inside the class, from objects, from child classes)
  • protected — accessible inside the class and child classes, but not from outside objects
  • private — accessible only inside the class itself
class BankAccount {
    public string $owner;
    protected float $balance;
    private string $accountNumber;

    public function __construct(string $owner, float $balance) {
        $this->owner         = $owner;
        $this->balance       = $balance;
        $this->accountNumber = 'ACC-' . rand(100000, 999999);
    }

    public function getBalance(): float {
        return $this->balance;  // Controlled access to private data
    }

    public function deposit(float $amount): void {
        if ($amount > 0) {
            $this->balance += $amount;
        }
    }
}

$account = new BankAccount('Lyndon', 5000.00);
echo $account->owner;           // Lyndon (public — OK)
echo $account->getBalance();    // 5000 (via public method — OK)
// echo $account->balance;      // Error: protected property
// echo $account->accountNumber; // Error: private property

Inheritance

Inheritance lets a class extend another class, inheriting all its properties and methods while adding or overriding its own:

class Animal {
    public string $name;

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

    public function speak(): string {
        return "{$this->name} makes a sound.";
    }
}

class Dog extends Animal {
    // Inherits $name and __construct from Animal
    // Overrides speak() with Dog-specific behavior
    public function speak(): string {
        return "{$this->name} says: Woof!";
    }

    // New method specific to Dog
    public function fetch(): string {
        return "{$this->name} fetches the ball!";
    }
}

class Cat extends Animal {
    public function speak(): string {
        return "{$this->name} says: Meow!";
    }
}

$dog = new Dog('Rex');
$cat = new Cat('Whiskers');

echo $dog->speak();    // Rex says: Woof!
echo $cat->speak();    // Whiskers says: Meow!
echo $dog->fetch();    // Rex fetches the ball!

Abstract Classes

An abstract class cannot be instantiated directly — it exists only to be extended. Abstract methods must be implemented by child classes:

abstract class Shape {
    abstract public function area(): float;
    abstract public function perimeter(): float;

    // Concrete method all shapes share
    public function describe(): string {
        return sprintf(
            "Area: %.2f, Perimeter: %.2f",
            $this->area(),
            $this->perimeter()
        );
    }
}

class Rectangle extends Shape {
    public function __construct(
        private float $width,
        private float $height
    ) {}

    public function area(): float {
        return $this->width * $this->height;
    }

    public function perimeter(): float {
        return 2 * ($this->width + $this->height);
    }
}

class Circle extends Shape {
    public function __construct(private float $radius) {}

    public function area(): float {
        return M_PI * $this->radius ** 2;
    }

    public function perimeter(): float {
        return 2 * M_PI * $this->radius;
    }
}

$rect   = new Rectangle(5, 3);
$circle = new Circle(4);

echo $rect->describe();   // Area: 15.00, Perimeter: 16.00
echo $circle->describe(); // Area: 50.27, Perimeter: 25.13

Interfaces

An interface defines a contract — a set of methods that any implementing class must provide. Unlike abstract classes, a class can implement multiple interfaces:

interface Serializable {
    public function toArray(): array;
    public function toJson(): string;
}

interface Validatable {
    public function isValid(): bool;
    public function errors(): array;
}

class UserProfile implements Serializable, Validatable {
    public function __construct(
        private string $name,
        private string $email,
        private int $age
    ) {}

    public function toArray(): array {
        return ['name' => $this->name, 'email' => $this->email, 'age' => $this->age];
    }

    public function toJson(): string {
        return json_encode($this->toArray());
    }

    public function isValid(): bool {
        return strlen($this->name) >= 2
            && filter_var($this->email, FILTER_VALIDATE_EMAIL)
            && $this->age >= 13;
    }

    public function errors(): array {
        $errors = [];
        if (strlen($this->name) < 2) $errors[] = 'Name too short';
        if (!filter_var($this->email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email';
        if ($this->age < 13) $errors[] = 'Must be at least 13';
        return $errors;
    }
}

$profile = new UserProfile('Lyndon', 'lyndon@example.com', 25);
echo $profile->toJson();           // {"name":"Lyndon","email":"...","age":25}
var_dump($profile->isValid());     // bool(true)

Static Methods and Properties

class Counter {
    private static int $count = 0;

    public static function increment(): void {
        self::$count++;
    }

    public static function getCount(): int {
        return self::$count;
    }
}

// Call without creating an object:
Counter::increment();
Counter::increment();
Counter::increment();

echo Counter::getCount(); // 3

Static methods are used for utility functions, factory methods, and singleton patterns. Laravel’s Facades are static-style interfaces to underlying objects.

READ ALSO:   WordPress Development for PHP Developers: Getting Started Guide (2026)

PHP 8 Constructor Property Promotion

PHP 8 introduced a shorthand for defining and assigning constructor parameters:

// Old way (verbose):
class Product {
    private string $name;
    private float $price;
    private int $stock;

    public function __construct(string $name, float $price, int $stock) {
        $this->name  = $name;
        $this->price = $price;
        $this->stock = $stock;
    }
}

// PHP 8 way (constructor promotion):
class Product {
    public function __construct(
        private string $name,
        private float $price,
        private int $stock
    ) {}
}

Both are equivalent. The PHP 8 version is dramatically shorter. You will see this pattern throughout Laravel’s codebase.

Traits — Reusable Code Blocks

PHP does not support multiple inheritance (a class can only extend one parent). Traits solve this by letting you include reusable method sets in any class:

trait Timestampable {
    private \DateTime $createdAt;
    private \DateTime $updatedAt;

    public function setTimestamps(): void {
        $this->createdAt = new \DateTime();
        $this->updatedAt = new \DateTime();
    }

    public function touch(): void {
        $this->updatedAt = new \DateTime();
    }

    public function getCreatedAt(): \DateTime {
        return $this->createdAt;
    }
}

trait SoftDeletable {
    private ?\DateTime $deletedAt = null;

    public function delete(): void {
        $this->deletedAt = new \DateTime();
    }

    public function isDeleted(): bool {
        return $this->deletedAt !== null;
    }
}

class Post {
    use Timestampable, SoftDeletable;

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

$post = new Post('My First Post');
echo $post->title;                    // My First Post
echo $post->getCreatedAt()->format('Y-m-d'); // Today's date
$post->delete();
var_dump($post->isDeleted());         // bool(true)

Practical OOP: A Simple Database Model

abstract class Model {
    protected static string $table = '';
    protected static \PDO $db;

    public static function setDb(\PDO $pdo): void {
        static::$db = $pdo;
    }

    public static function find(int $id): ?array {
        $stmt = static::$db->prepare(
            "SELECT * FROM " . static::$table . " WHERE id = ?"
        );
        $stmt->execute([$id]);
        return $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
    }

    public static function all(): array {
        return static::$db
            ->query("SELECT * FROM " . static::$table)
            ->fetchAll(\PDO::FETCH_ASSOC);
    }
}

class User extends Model {
    protected static string $table = 'users';
}

class Post extends Model {
    protected static string $table = 'posts';
}

// Usage:
$pdo = new \PDO('mysql:host=localhost;dbname=myapp', 'root', '');
Model::setDb($pdo);

$user  = User::find(1);
$posts = Post::all();

This is a simplified version of what Laravel’s Eloquent ORM does under the hood — each model class represents a database table, and static methods provide querying capabilities.

READ ALSO:   PHP Undefined Variable Error: Causes and Fixes

Next Steps

After mastering PHP OOP basics, your natural next step is learning a PHP framework. Laravel uses all of these concepts extensively — every controller, model, and service you write in Laravel is a PHP class. The OOP patterns from this tutorial map directly to real Laravel development.

Conclusion

PHP OOP makes code organized, reusable, and maintainable. The core concepts — classes, objects, access modifiers, inheritance, interfaces, and traits — appear throughout every PHP framework and modern codebase. Practice these examples, build a small project using them, and you will be ready to start working with Laravel or any other professional PHP framework.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment