PHP OOP – Inheritance (উত্তরাধিকার)

PHP OOP – Inheritance (উত্তরাধিকার)

Inheritance বা উত্তরাধিকার হচ্ছে Object-Oriented Programming (OOP) এর একটি গুরুত্বপূর্ণ বৈশিষ্ট্য। এর মাধ্যমে একটি ক্লাস (child class) আরেকটি ক্লাসের (parent class) প্রপার্টি ও মেথড ব্যবহার করতে পারে। এটি কোড রিইউজ এবং রক্ষণাবেক্ষণ সহজ করে।

Inheritance এর মূল ধারণা

PHP-তে extends কীওয়ার্ড ব্যবহার করে একটি ক্লাসকে অন্য ক্লাস থেকে Inherit করা হয়।

উদাহরণ ১: Basic Inheritance


<?php
class Animal {
    public function makeSound() {
        echo "Some generic animal sound";
    }
}

class Dog extends Animal {
    public function bark() {
        echo "Dog says: Woof!";
    }
}

$dog = new Dog();
$dog->makeSound(); // Inherited method
echo "<br>";
$dog->bark();       // Own method
?>
    

⚡ এখানে Dog ক্লাস Animal থেকে উত্তরাধিকার পেয়েছে। ফলে Dog ক্লাস makeSound() মেথডটি ব্যবহার করতে পারছে।

উদাহরণ ২: Overriding

সাব ক্লাস চাইলে parent ক্লাসের মেথডকে নিজের মতো করে পরিবর্তন করতে পারে, একে বলে Method Overriding।


<?php
class Vehicle {
    public function start() {
        echo "Starting vehicle...";
    }
}

class Car extends Vehicle {
    public function start() {
        echo "Starting car engine...";
    }
}

$obj = new Car();
$obj->start(); // Output: Starting car engine...
?>
    

✅ এখানে Car ক্লাস start() মেথডটি ওভাররাইড করে নিজস্বভাবে ব্যবহার করছে।

Parent ও Child ক্লাসের তুলনা

পার্থক্য Parent Class Child Class
উত্তরাধিকার দেয় হ্যাঁ না
মেথড ওভাররাইড করে? না হ্যাঁ
extends ব্যবহার হয়? না হ্যাঁ

উদাহরণ ৩: Constructor Inheritance

Constructor ও Inheritance একসাথে ব্যবহার করা যায়। নিচে দেখুন:


<?php
class Father {
    function __construct() {
        echo "Father's constructor called<br>";
    }
}

class Son extends Father {
    function __construct() {
        parent::__construct();
        echo "Son's constructor called";
    }
}

$son = new Son();
?>
    

➡️ এখানে parent::__construct() ব্যবহার করে parent constructor-কে invoke করা হয়েছে।


 

Leave a Reply