🏠 Home / Hub

🐘 PHP Lesson 08 — OOP: Classes & Objects

← Back to PHP Menu  |  🏠 Hub

1. PHP OOP အခြေခံ

PHP မှာ OOP = class, object, inheritance, interface, trait တွေပါ
Laravel, Symfony, WordPress plugins — အကုန် OOP ပဲ
PHP 8.0+ — constructor promotion, match expression, named args ထပ်လာပြီ
<?php

// Class definition
class BankAccount {
    // Properties — visibility: public / protected / private
    public string $owner;
    private float $balance;
    private array $transactions = [];

    // Constructor — object ဆောက်တဲ့အခါ auto call
    public function __construct(string $owner, float $initialBalance = 0) {
        $this->owner   = $owner;
        $this->balance = $initialBalance;
    }

    // Public method
    public function deposit(float $amount): string {
        if ($amount <= 0) {
            throw new InvalidArgumentException("Amount must be positive");
        }
        $this->balance += $amount;
        $this->transactions[] = "+$amount";
        return "Deposited: $amount. Balance: {$this->balance}";
    }

    public function withdraw(float $amount): string {
        if ($amount > $this->balance) {
            return "Insufficient funds!";
        }
        $this->balance -= $amount;
        $this->transactions[] = "-$amount";
        return "Withdrew: $amount. Balance: {$this->balance}";
    }

    public function getBalance(): float { return $this->balance; }
    public function getInfo(): string   { return "{$this->owner}: \${$this->balance}"; }

    // Private helper — outside မသုံးနိုင်
    private function logTransaction(string $msg): void {
        $this->transactions[] = $msg;
    }
}

// Object တည်ဆောက်ခြင်း
$acc1 = new BankAccount("Ko Ko", 1000.00);
$acc2 = new BankAccount("Ma Ma");  // balance = 0

echo $acc1->deposit(500);    // "Deposited: 500. Balance: 1500"
echo $acc1->withdraw(200);   // "Withdrew: 200. Balance: 1300"
echo $acc2->getInfo();       // "Ma Ma: $0"

// Properties access
echo $acc1->owner;    // "Ko Ko"  (public — OK)
// echo $acc1->balance; ❌ Fatal Error: private

2. Constructor Promotion (PHP 8.0+)

<?php

// Old way — verbose
class UserOld {
    public string $name;
    public string $email;
    private int $age;

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

// PHP 8.0+ constructor promotion — same result, shorter!
class User {
    public function __construct(
        public readonly string $name,    // readonly = can't change after set
        public string $email,
        private int $age = 18
    ) {}  // no body needed!

    public function isAdult(): bool { return $this->age >= 18; }
    public function getAge(): int   { return $this->age; }
}

$user = new User("Ko Ko", "ko@example.com", 25);
echo $user->name;        // "Ko Ko"
echo $user->email;       // "ko@example.com"
echo $user->isAdult();   // true

// readonly — cannot change
// $user->name = "New Name"; ❌ Error!

3. Static Properties & Methods

<?php

class Counter {
    private static int $count = 0;    // shared across all instances
    private int $id;

    public function __construct() {
        self::$count++;          // self:: = this class
        $this->id = self::$count;
    }

    // Static method — instance မဆောက်ဘဲ ခေါ်လို့ရ
    public static function getCount(): int {
        return self::$count;
    }

    public static function reset(): void {
        self::$count = 0;
    }

    public function getId(): int { return $this->id; }
}

$a = new Counter();   // count = 1
$b = new Counter();   // count = 2
$c = new Counter();   // count = 3

echo Counter::getCount();  // 3  (:: = scope resolution)
echo $a->getId();          // 1
echo $b->getId();          // 2

Counter::reset();
echo Counter::getCount();  // 0

4. Getters & Setters / Magic Methods

<?php

class Product {
    private float $price;
    private string $name;
    private array $data = [];

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

    // Getter with validation
    public function getPrice(): float  { return $this->price; }
    public function getName(): string  { return $this->name; }

    // Setter with validation
    public function setPrice(float $price): void {
        if ($price < 0) throw new \InvalidArgumentException("Price cannot be negative");
        $this->price = $price;
    }

    // Magic methods
    public function __toString(): string {
        return "{$this->name}: \${$this->price}";
    }

    // __get / __set — dynamic properties
    public function __get(string $key): mixed {
        return $this->data[$key] ?? null;
    }

    public function __set(string $key, mixed $value): void {
        $this->data[$key] = $value;
    }

    // __destruct — object ဖျက်ချိန် call
    public function __destruct() {
        // cleanup
    }
}

$p = new Product("Book", 29.99);
echo $p;              // "Book: $29.99"  (uses __toString)
echo $p->getPrice();  // 29.99

$p->color = "Blue";   // uses __set
echo $p->color;       // "Blue"  uses __get
💡 PHP Magic Methods: __construct, __destruct, __toString, __get, __set, __call, __clone, __invoke

5. Constants in Class

<?php

class OrderStatus {
    // Class constants
    const PENDING   = 'pending';
    const CONFIRMED = 'confirmed';
    const SHIPPED   = 'shipped';
    const DELIVERED = 'delivered';
    const CANCELLED = 'cancelled';

    // PHP 8.1+ Enum (better than constants!)
    // enum Status { case Pending; case Confirmed; ... }

    public static function getAll(): array {
        return [
            self::PENDING,
            self::CONFIRMED,
            self::SHIPPED,
            self::DELIVERED,
            self::CANCELLED,
        ];
    }

    public static function isValid(string $status): bool {
        return in_array($status, self::getAll(), true);
    }
}

echo OrderStatus::PENDING;          // "pending"
OrderStatus::isValid("shipped");    // true
OrderStatus::isValid("unknown");    // false

// Typed constants (PHP 8.3+)
class Config {
    const int MAX_RETRIES = 3;
    const string VERSION  = "1.0.0";
    const float TIMEOUT   = 30.0;
}

📌 Visibility Cheat Sheet

VisibilitySame ClassChild ClassOutside
public
protected
private

← PHP 07  |  Next: PHP 09 → Inheritance →

📌 Study Checklist