PHP 5.0物件模型深度探索之對象複製

來源:互聯網
上載者:User
對象     PHP5中的物件模型通過引用來調用對象, 但有時你可能想建立一個對象的副本,並希望原來的對象的改變不影響到副本 . 為了這樣的目的,PHP定義了一個特殊的方法,稱為__clone. 像__construct和__destruct一樣,前面有兩個底線。

  預設地,用__clone方法將建立一個與原對象擁有相同屬性和方法的對象. 如果你想在複製時改變預設的內容,你要在__clone中覆寫(屬性或方法)。

  複製的方法可以沒有參數,但它同時包含this和that指標(that指向被複製的對象)。如果你選擇複製自己,你要小心複製任何你要你的對象包含的資訊,從that到this,如果你用__clone來複製,PHP不會執行任何隱性的複製,下面顯示了一個用系列序數來Automation 物件的例子:

class ObjectTracker //對象跟蹤器
{
 private static $nextSerial = 0;
 private $id;
 private $name;

 function __construct($name) //建構函式
 {
  $this->name = $name;
  $this->id = ++self::$nextSerial;
 }

 function __clone() //複製
 {
  $this->name = "Clone of $this->name";
  $this->id = ++self::$nextSerial;
 }

 function getId() //擷取id屬性的值
 {
  return($this->id);
 }

 function getName() //擷取name屬性的值
 {
  return($this->name);
 }
}

$ot = new ObjectTracker("Zeev's Object");
$ot2 = clone$ot;

//輸出: 1 Zeev's Object
print($ot->getId() . " " . $ot->getName() . "");

//輸出: 2 Clone of Zeev's Object
print($ot2->getId() . " " . $ot2->getName() . "");
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.