# কনস্ট্রাক্টর এবং ডেস্ট্রাক্টর

## কন্সট্রাক্টরস

যে কোন ক্লাসে আমরা একটি বিশেষ মেথড ডিফাইন করে দিতে পারি । পিএইচপি যখন একটি ক্লাস থেকে অবজেক্ট ইন্সট্যান্স তৈরি করবে তখন নতুন তৈরি হওয়া অবজেক্টটির এই বিশেষ মেথডটি কল করবে । প্রত্যেকটি ইন্সট্যান্স তৈরি হওয়র পরপরই পিএইচপি এই মেথডটি কল করে বিধায় অবজেক্টের নানা বিধ ইনিশিয়ালাইজেশনের কাজ এই মেথডে করা সম্ভব । এই মেথডটি অবজেক্ট তৈরি করার সময় গুরুত্বপূর্ন ভূমিকা পালন করে বিধায় এটাকে কন্সট্রাক্টর ফাংশন বা মেথড বলে ।

আমরা একটি উদাহরন দেখি:

```php
<?php
class TestClass {
   function __construct() {
       print "From the constructor\n";
   }
}

$bc = new TestClass();
```

## কন্সট্রাক্টরস ও ইনহেরিট্যান্স

চাইল্ড ক্লাস গুলোতে যদি আমরা নিজেদের কনস্ট্রাক্টর ডিফাইন করি তাহলে আর প্যারেন্ট এর কন্সট্রাক্টর অটোমেটিক্যালি কল হয় না । আমাদের কে এক্সপ্লিসিটলি প্যারেন্ট এর কন্সট্রাক্টর কল করার প্রয়োজন হয়।

```php
<?php
class TestClass {
   function __construct() {
       print "From the constructor\n";
   }
}

class SubClass extends TestClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

$test = new SubClass();
```

এখানে `parent::__construct();` এর মাধ্যমে আমরা প্যারেন্ট এর কন্সট্রাক্টর কল করলাম ।

## ডেস্ট্রাক্টরস

একটা অবজেক্ট এর কাজ যখন শেষ হয়ে যায়, যখন আর কোন রেফারেন্স থাকে না ঐ অবজেক্ট এর তখন ঐ অবজেক্ট এর ডেস্ট্রাক্টর মেথডটি কল করা হয় ।

```php
<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
```

সাধারনত অবজেক্ট এ ব্যবহৃত গুরুত্বপূর্ন রিসোর্স ডি-এ্যালোকেট করার জন্য ডেস্ট্রাক্টর মেথড বেশ কাজে দেয় । কনস্ট্রাক্টর এর মত ডেস্ট্রাক্টরের বেলায় প্যারেন্ট এর ডেস্ট্রাক্টর এক্সপ্লিসিটলি কল করতে হয় ।


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://php.howtocode.dev/oop/oop-constructors-and-destructors.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
