🧰 PHP Object-Oriented Programming: Classes, Objects, Inheritance, Traits Explained

Object-Oriented Programming (OOP) in PHP introduces powerful features that help you build modular, reusable, and maintainable code. PHP OOP allows developers to structure software like real-world entities using classes and objects.


🧠 PHP OOP Introduction

OOP (Object-Oriented Programming) in PHP lets you build applications by organizing code into classes and objects, rather than just procedures and functions.

class Car {
    public $brand = "Toyota";
}

$car = new Car();
echo $car->brand; // Toyota

🧱 PHP Classes and Objects

  • Class: Blueprint for an object.
  • Object: Instance of a class.
class Person {
    public $name;

    function greet() {
        return "Hello, I'm " . $this->name;
    }
}

$p = new Person();
$p->name = "Alice";
echo $p->greet();

🚪 PHP Constructor and Destructor

  • Constructor: Automatically called when an object is created.
  • Destructor: Called when there are no more references to the object.
class Animal {
    function __construct() {
        echo "Animal created!";
    }
    
    function __destruct() {
        echo "Animal destroyed!";
    }
}

🔐 PHP Access Modifiers

  • public: Accessible everywhere
  • protected: Accessible in class and subclasses
  • private: Accessible only within the class
class BankAccount {
    private $balance = 1000;

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

🔁 PHP Inheritance

Child classes can inherit properties and methods from a parent class.

class ParentClass {
    protected function sayHello() {
        echo "Hello from Parent!";
    }
}

class ChildClass extends ParentClass {
    public function greet() {
        $this->sayHello();
    }
}

🧳 PHP Encapsulation

Encapsulation hides internal object details and exposes only what’s necessary using methods.

class Box {
    private $item;

    public function setItem($item) {
        $this->item = $item;
    }

    public function getItem() {
        return $this->item;
    }
}

🧱 PHP Final Keyword

The final keyword prevents classes or methods from being extended or overridden.

final class Base {}

class Sub extends Base {} // ❌ Error

🔒 PHP Class Constants

Use const to define constants inside a class.

class App {
    const VERSION = "1.0";
}

echo App::VERSION;

🧰 PHP Abstract Classes

Used to define base templates. Cannot be instantiated.

abstract class Shape {
    abstract public function area();
}

class Circle extends Shape {
    public function area() {
        return 3.14 * 5 * 5;
    }
}

🔌 PHP Interfaces

Interfaces define required methods without implementation.

interface Logger {
    public function log($msg);
}

class FileLogger implements Logger {
    public function log($msg) {
        echo "Logged: $msg";
    }
}

🧬 PHP Traits

Traits allow reusing methods across classes without inheritance.

trait Sharable {
    public function share() {
        return "Shared!";
    }
}

class Post {
    use Sharable;
}

🧿 PHP Static Methods

Static methods can be called without an instance.

class Math {
    public static function square($x) {
        return $x * $x;
    }
}

echo Math::square(4);

💾 PHP Static Properties

Shared across all instances.

class Counter {
    public static $count = 0;

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

🗂️ PHP Namespaces

Avoid class name conflicts by organizing code into namespaces.

namespace MyApp\Models;

class User {}

🔄 PHP Object Iteration

Iterate through object properties using foreach.

class Book {
    public $title = "PHP";
    public $author = "John";
}

$book = new Book();
foreach ($book as $key => $value) {
    echo "$key: $value\n";
}

♻️ PHP Overloading

Using __get, __set, __call to define dynamic behavior.

class Demo {
    private $data = [];

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    public function __get($name) {
        return $this->data[$name];
    }
}

📋 PHP Cloning Objects

Use clone to duplicate objects.

class Item {
    public $name = "Box";
}

$copy = clone new Item();

🕵️ PHP Anonymous Classes

Classes defined without a name; useful for one-time use.

$logger = new class {
    public function log($msg) {
        echo "Log: $msg";
    }
};

$logger->log("Success");

✅ Summary

PHP’s Object-Oriented Programming enables cleaner, modular, and scalable code. From basic classes to advanced traits and interfaces, mastering OOP is essential for building modern PHP applications.


❓ FAQ

Q1. What is the difference between abstract class and interface?
Abstract classes can include implementation; interfaces only define method signatures.

Q2. When should I use traits in PHP?
Use traits to share common methods between unrelated classes, avoiding multiple inheritance.

Q3. What is encapsulation in PHP?
Encapsulation hides object details using private/protected members and provides access via public methods.


Share Now :
Share

🔒 PHP Class Constants

Or Copy Link

CONTENTS
Scroll to Top