مجیک متد
__clone() :این متد برای ایجاد نسخه ای کپی از یک شئ استفاده میشود. وقتی از عملگر کلون (
clone) استفاده میکنید، تابع __clone() در کلاس مربوطه اجرا میشود و میتوانید تنظیمات مورد نیاز برای نسخه کپی را انجام دهید.مثال :
class Fruit {
public $name;
public $color;
public function __clone() {
$this->name = 'cloned fruit name';
$this->color = 'cloned fruit color';
}
}
$firstFruit = new Fruit();
$firstFruit->name = 'banana';
$firstFruit->color = 'red';
$clonedFruit = clone $firstFruit;
var_dump($firstFruit);
var_dump($clonedFruit);
Result:object(Fruit)#1 (2) {
["name"]=>
string(6) "banana"
["color"]=>
string(3) "red"
}
object(Fruit)#2 (2) {
["name"]=>
string(17) "cloned fruit name"
["color"]=>
string(18) "cloned fruit color"
}
در مثال بالا یک شئ از
Fruit با دو ویژگی name و color ساخته ایم و سپس یک clone از آن گرفته ایم، زمان استفاده از عملگر clone متد __clone() فراخوانی می شود و شئ جدید را با ویژگی های تنظیم شده می سازد..