Kaedah __clone
Kaedah __clone dipanggil secara automatik apabila menggunakan operator clone.
Ia membolehkan anda menentukan logik penyalinan objek sendiri. Secara lalai, PHP
melakukan penyalinan cetusan semua sifat objek. Kaedah __clone berguna
apabila perlu melaksanakan penyalinan mendalam atau mengubah tingkah laku semasa pengklonan.
Sintaks
public function __clone(): void
Contoh
Laksanakan pengklonan objek asas:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function __clone() {
echo 'Objek diklon';
}
}
$user1 = new User('John');
$user2 = clone $user1;
?>
Keputusan pelaksanaan kod:
'Objek diklon'
Contoh
Laksanakan penyalinan mendalam objek dengan objek bersarang:
<?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;
?>
Keputusan pelaksanaan kod:
'New York'
Contoh
Tambahkan pengecam unik semasa pengklonan:
<?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;
?>
Keputusan pelaksanaan kod (contoh):
'5f1a2b3c 5f1a2b3d'
Lihat juga
-
kaedah
__construct,
yang merupakan pembina objek