Polymorphism মানে কোড ভিন্ন type-এর object-এ একই method নাম call করতে পারে, আর প্রতিটি নিজের version চালায় — আগের Interfaces lesson ইতিমধ্যে বাস্তবে এটা বানায়; এই lesson concept-টার নাম দেয় আর এর উপর নির্ভর করা নিরাপদ বানায় এমন type declaration কভার করে।
interface Shape {
public function area(): float;
}
class Circle implements Shape {
public function __construct(private float $radius) {}
public function area(): float {
return pi() * $this->radius ** 2;
}
}
class Rectangle implements Shape {
public function __construct(private float $width, private float $height) {}
public function area(): float {
return $this->width * $this->height;
}
}
function printArea(Shape $shape): void {
echo $shape->area() . PHP_EOL;
}
printArea(new Circle(5));
printArea(new Rectangle(4, 6));
// printArea কোন shape পেয়েছে জানে না বা পরোয়া করে না —
// প্রতিটি নিজের area() সঠিকভাবে হিসাব করেShape $shape parameter type-ই এটাকে নিরাপদ বানায় — PHP গ্যারান্টি দেয় পাঠানো যেকোনো কিছুর একটি area() method আছে, printArea-কে এটা কোন ধরনের shape পেয়েছে তা check করতে হয় না।
| কোথায় | উদাহরণ |
|---|---|
| Parameter type | function area(Shape $shape) |
| Return type | function area(): float |
| Property type | private float $radius; |
| Union type — একাধিক অনুমোদিত | function process(int|string $id) |
| Nullable type | function find(int $id): ?User |
printArea(Shape $shape) যেমন করে একটি interface type-hint করা dependency injection-এরও ভিত্তি — একটি নির্দিষ্ট ক্লাসের বদলে একটি interface-এর উপর নির্ভর করা একটি ক্লাসে যেকোনো মিলে যাওয়া implementation "inject" করা যায়, যা ক্লাস নিজে না বদলেই একটি আসল database-কে একটি test double দিয়ে বদলানো সম্ভব করে। এটা নিজেই একটি পূর্ণ topic, এখন নাম আর ধারণাটা জানার যোগ্য।
PHP-র typing runtime-checked
PHP compile time-এ না, runtime-এ type check করে — একটি ভুল type এখনো একটি error ঘটায়, শুধু script শুরু হওয়ার আগে না, ওই কোড লাইনটা আসলে চলার সময়।