ක්රමය __clone
මෙම ක්රමය __clone ක්ලෝන් ක්රියාකරු භාවිතා කරන විට ස්වයංක්රීයව ක්රියාත්මක වේ.
එය වස්තුව පිටපත් කිරීම සඳහා තමන්ගේම තර්කනය අර්ථ දැක්වීමට ඉඩ සලසයි. පෙරනිමිය අනුව, PHP
වස්තුවේ සියලු ගුණාංග ගැඹුරු නොවන පිටපත් කිරීමක් සිදු කරයි. මෙම ක්රමය __clone ප්රයෝජනවත් වන්නේ
ගැඹුරු පිටපත් කිරීම ක්රියාත්මක කිරීමට හෝ පිටපත් කිරීමේදී හැසිරීම වෙනස් කිරීමට අවශ්ය විට ය.
වාක්ය රචනා ක්රමය
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;
?>
කේතය ක්රියාත්මක කිරීමේ ප්රතිඵලය:
'වස්තුව පිටපත් කරන ලදී'
උදාහරණය
තවත් වස්තූන් අඩංගු වස්තුවක් ගැඹුරට පිටපත් කිරීම ක්රියාත්මක කරමු:
<?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,
වස්තුවේ ගොඩනැගීමේ ක්රමය වේ