استنساخ PHP Keyword
مثال
إنشاء نسخة من كائن:
<?php
class MyClass {
public $color;
public $amount;
}
$obj = new MyClass();
$obj->color = "red";
$obj->amount = 5;
$copy = clone $obj;
print_r($copy);
?>
التعريف والاستخدام
يتم clone
استخدام الكلمة الأساسية لإنشاء نسخة من كائن.
إذا كانت أي من الخصائص تشير إلى متغير أو كائن آخر ، فسيتم نسخ المرجع فقط. يتم تمرير الكائنات دائمًا عن طريق المرجع ، لذلك إذا كان الكائن الأصلي يحتوي على كائن آخر في خصائصه ، فستشير النسخة إلى نفس الكائن. يمكن تغيير هذا السلوك عن طريق إنشاء __clone()
طريقة في الفصل.
الصفحات ذات الصلة
اقرأ المزيد عن الفصول في دروسنا في دروس وكائنات PHP .
مزيد من الأمثلة
مثال
قم بإنشاء نسخة من كائن له مرجع:
<?php
class MyClass {
public $amount;
}
// Create an object with a
reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
// Clone the object
$copy = clone $obj;
// Change the value in the
original object
$obj->amount = 6;
// The copy is changed
print_r($copy);
?>
مثال
استخدم __clone()
طريقة لكسر المراجع في كائن منسوخ:
<?php
class MyClass {
public $amount;
public function __clone() {
$value = $this->amount;
unset($this->amount); // Unset breaks references
$this->amount = $value;
}
}
// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
// Clone
the object
$copy = clone $obj;
// Change the value in the original
object
$obj->amount = 6;
// The copy is not changed
print_r($copy);
?>
❮ كلمات PHP