Constructor কী?
Constructor হলো একটি বিশেষ method যা object তৈরির সময় স্বয়ংক্রিয়ভাবে কল হয়। PHP-তে এর নাম __construct()।
Constructor ছাড়া সমস্যা
class Student {
public $name;
public $roll;
}
$s = new Student();
$s->name = "করিম"; // আলাদা আলাদা লাইনে
$s->roll = 42; // সেট করতে হচ্ছে
// ৫০টি student হলে? — অনেক বিরক্তিকর
Constructor দিয়ে সমাধান
class Student {
public $name;
public $roll;
// Constructor
public function __construct($name, $roll) {
$this->name = $name;
$this->roll = $roll;
echo "Student {$name} তৈরি হলো\n";
}
public function info() {
echo "নাম: {$this->name}, রোল: {$this->roll}\n";
}
}
// Object তৈরি — constructor স্বয়ংক্রিয়ভাবে কল হবে
$s1 = new Student("করিম", 1);
$s2 = new Student("রহিম", 2);
$s3 = new Student("জামিল", 3);
$s1->info(); // নাম: করিম, রোল: 1
Default Parameter সহ Constructor
class User {
public $username;
public $role;
public function __construct($username, $role = "user") {
$this->username = $username;
$this->role = $role;
}
}
$u1 = new User("করিম"); // role = "user" (default)
$u2 = new User("admin1", "admin");
Constructor Property Promotion (PHP 8+)
PHP 8-এ constructor এ সরাসরি property declare করা যায় — অনেক কম কোড।
// পুরনো
class Product {
public $name;
public $price;
public $stock;
public function __construct($name, $price, $stock) {
$this->name = $name;
$this->price = $price;
$this->stock = $stock;
}
}
// নতুন (PHP 8+) ⭐
class Product {
public function __construct(
public string $name,
public float $price,
public int $stock = 0
) {}
}
$p = new Product("বই", 250.50, 10);
echo $p->name; // বই
Destructor
Destructor object যখন memory থেকে মুছে যায় তখন স্বয়ংক্রিয়ভাবে কল হয়। এটি __destruct()। সাধারণত cleanup কাজে (ফাইল বন্ধ, DB disconnect) ব্যবহৃত হয়।
class FileHandler {
private $file;
public function __construct($filename) {
$this->file = fopen($filename, "r");
echo "ফাইল খোলা হলো\n";
}
public function __destruct() {
fclose($this->file);
echo "ফাইল বন্ধ হলো\n";
}
}
$fh = new FileHandler("data.txt");
// Script শেষে destructor স্বয়ংক্রিয়ভাবে কল হবে
বাস্তব উদাহরণ: Database Connection
class DB {
private $conn;
public function __construct($host, $user, $pass, $db) {
$this->conn = new mysqli($host, $user, $pass, $db);
if ($this->conn->connect_error) {
die("সংযোগ ব্যর্থ: " . $this->conn->connect_error);
}
echo "DB সংযুক্ত হয়েছে\n";
}
public function __destruct() {
$this->conn->close();
echo "DB বিচ্ছিন্ন হয়েছে\n";
}
}
$db = new DB("localhost", "root", "", "mydb");