__clone মেথড
মেথড __clone স্বয়ংক্রিয়ভাবে কল হয় যখন clone অপারেটর ব্যবহার করা হয়।
এটি অবজেক্ট কপি করার নিজস্ব লজিক নির্ধারণ করতে দেয়। ডিফল্টভাবে PHP
অবজেক্টের সব প্রপার্টির shallow কপি করে। __clone মেথডটি উপকারী
যখন deep কপি বাস্তবায়ন করা প্রয়োজন বা ক্লোন করার সময় আচরণ পরিবর্তন করা প্রয়োজন।
সিনট্যাক্স
public function __clone(): void
উদাহরণ
আসুন একটি অবজেক্টের বেসিক ক্লোনিং বাস্তবায়ন করি:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function __clone() {
echo 'অবজেক্ট ক্লোন করা হয়েছে';
}
}
$user1 = new User('John');
$user2 = clone $user1;
?>
কোড 실행ের ফলাফল:
'অবজেক্ট ক্লোন করা হয়েছে'
উদাহরণ
নেস্টেড অবজেক্ট সহ একটি অবজেক্টের deep কপি বাস্তবায়ন করি:
<?php
class Address {
public $city;
public function __construct($city) {
$this->city = $city;
}
}
class User {
public $name;
public $address;
public function __construct($name, $city) {
$this->name = $name;
$this->address = new Address($city);
}
public function __clone() {
$this->address = clone $this->address;
}
}
$user1 = new User('John', 'New York');
$user2 = clone $user1;
$user2->address->city = 'Boston';
echo $user1->address->city;
?>
কোড 실행ের ফলাফল:
'New York'
উদাহরণ
ক্লোন করার সময় একটি অনন্য আইডেন্টিফায়ার যোগ করি:
<?php
class Product {
public $id;
public $name;
public function __construct($name) {
$this->id = uniqid();
$this->name = $name;
}
public function __clone() {
$this->id = uniqid();
}
}
$product1 = new Product('Laptop');
$product2 = clone $product1;
echo $product1->id . ' ' . $product2->id;
?>
কোড 실행ের ফলাফল (উদাহরণ):
'5f1a2b3c 5f1a2b3d'
আরও দেখুন
-
মেথড
__construct,
যা অবজেক্টের কনস্ট্রাক্টর