Polymorphism ও Abstraction

লেসন ৬ / ৩৯

Polymorphism কী?

Polymorphism মানে "বহুরূপ" — একই নামের method বিভিন্ন class-এ বিভিন্নভাবে কাজ করে। Inheritance ও method overriding-এর মাধ্যমে অর্জিত হয়।

class Shape {
    public function area() {
        return 0;
    }
}

class Circle extends Shape {
    public $radius;
    public function __construct($r) { $this->radius = $r; }

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

class Rectangle extends Shape {
    public $width, $height;
    public function __construct($w, $h) {
        $this->width = $w;
        $this->height = $h;
    }

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

// Polymorphism সৌন্দর্য ⭐
$shapes = [
    new Circle(5),
    new Rectangle(4, 6),
    new Circle(3),
];

foreach ($shapes as $shape) {
    echo $shape->area() . "\n";
}
// একই method call, ভিন্ন ফলাফল!

Abstract Class

Abstract class এমন class যাকে directly instantiate করা যায় না। এটি একটি "অসম্পূর্ণ template" — child class-কে সম্পূর্ণ করতে হয়।

abstract class Animal {
    protected $name;

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

    // সাধারণ method (implemented)
    public function sleep() {
        echo "{$this->name} ঘুমাচ্ছে\n";
    }

    // Abstract method (child-কে implement করতে হবে)
    abstract public function sound();
}

// ❌ $a = new Animal("কুকুর");  // Error!

class Dog extends Animal {
    public function sound() {
        echo "{$this->name}: ঘেউ ঘেউ\n";
    }
}

class Cat extends Animal {
    public function sound() {
        echo "{$this->name}: মিউ\n";
    }
}

$d = new Dog("টমি");
$d->sound();   // টমি: ঘেউ ঘেউ
$d->sleep();   // টমি ঘুমাচ্ছে

Interface

Interface হলো একটি "চুক্তি" — class-কে যা যা method implement করতে হবে তার তালিকা। Body থাকে না।

interface Payable {
    public function pay($amount);
    public function refund($amount);
}

interface Loggable {
    public function log($message);
}

// Multiple interface implement করা যায় ⭐
class Order implements Payable, Loggable {
    public function pay($amount) {
        echo "{$amount} টাকা পরিশোধ করা হলো\n";
    }

    public function refund($amount) {
        echo "{$amount} টাকা ফেরত\n";
    }

    public function log($message) {
        echo "LOG: {$message}\n";
    }
}

$o = new Order();
$o->pay(500);
$o->log("Order 42 paid");

Abstract Class vs Interface

Abstract ClassInterface
কিছু method implemented থাকতে পারেসব method abstract
Properties থাকতে পারেশুধু constant থাকতে পারে
একটি extend করা যায়একাধিক implement করা যায়
"is-a" সম্পর্ক"can-do" সম্পর্ক

Trait (Multiple Inheritance-এর বিকল্প)

trait Sharable {
    public function share() {
        echo "শেয়ার করা হলো\n";
    }
}

trait Printable {
    public function print() {
        echo "প্রিন্ট করা হলো\n";
    }
}

class Post {
    use Sharable, Printable;  // দুটোই ব্যবহার
}

$p = new Post();
$p->share();   // শেয়ার করা হলো
$p->print();   // প্রিন্ট করা হলো