Metodi __clone
Metodi __clone thirret automatikisht kur përdoret operatori clone.
Ai lejon përcaktimin e logjikës së vet për kopjimin e objektit. Si parazgjedhje, PHP
kryen një kopjim sipërfaqësor të të gjitha vetive të objektit. Metodi __clone është i dobishëm
kur duhet të implementohet kopjim i thellë ose të ndryshohet sjellja gjatë klonimit.
Sintaksa
public function __clone(): void
Shembull
Le të implementojmë klonimin bazë të një objekti:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function __clone() {
echo 'Objekti u klonua';
}
}
$user1 = new User('John');
$user2 = clone $user1;
?>
Rezultati i ekzekutimit të kodit:
'Objekti u klonua'
Shembull
Le të implementojmë kopjim të thellë të një objekti me objekte të mbivendosur:
<?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;
?>
Rezultati i ekzekutimit të kodit:
'New York'
Shembull
Le të shtojmë një identifikues unik gjatë klonimit:
<?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;
?>
Rezultati i ekzekutimit të kodit (shembull):
'5f1a2b3c 5f1a2b3d'
Shihni gjithashtu
-
metodi
__construct,
i cili është konstruktor i objektit