နည်းလမ်း __clone
နည်းလမ်း __clone ကို clone လုပ်ဆောင်ချက် သင်္ကေတကို အသုံးပြုသောအခါ အလိုအလျောက် ခေါ်ယူခြင်းခံရသည်။
၎င်းသည် object ကို ကူးယူခြင်း၏ ကိုယ်ပိုင် ယုတ္တိကို သတ်မှတ်ပေးခွင့်ပြုသည်။ ပုံမှန်အားဖြင့် PHP သည်
object ၏ ဂုဏ်သတ္တိအားလုံးကို အပေါ်ယံကူးယူခြင်း ပြုလုပ်သည်။ နည်းလမ်း __clone သည်
နက်ရှိုင်းစွာ ကူးယူခြင်း သို့မဟုတ် ပုံတူကူးသည့်အခါ အပြုအမူကို ပြောင်းလဲလိုသည့်အခါမျိုးတွင် အသုံးဝင်သည်။
ဝါကျဖွဲ့ပုံ
public function __clone(): void
ဥပမာ
Object ၏ အခြေခံ ပုံတူကူးခြင်းကို အကောင်အထည်ဖော်ကြမည်။
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function __clone() {
echo 'Object ကို ပုံတူကူးပြီးပါပြီ';
}
}
$user1 = new User('John');
$user2 = clone $user1;
?>
ကုဒ် လုပ်ဆောင်ချက်၏ ရလဒ်။
'Object ကို ပုံတူကူးပြီးပါပြီ'
ဥပမာ
အတွင်းထဲတွင် object များ ထည့်သွင်းထားသော object တစ်ခုကို နက်ရှိုင်းစွာ ကူးယူခြင်းကို အကောင်အထည်ဖော်ကြမည်။
<?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,
အကြောင်းမှာ ၎င်းသည် object ၏ တည်ဆောက်သူ ဖြစ်သောကြောင့်ဖြစ်သည်