[資料]PHP中的clone使用

來源:互聯網
上載者:User
文章目錄
  • PHP中的clone使用
PHP中的clone使用

官方文檔:http://cn2.php.net/__clone

在多數情況下,我們並不需要完全複製一個對象來獲得其中屬性。但有一個情況下確實需要:如果你有一個 GTK視窗對象,該對象持有視窗相關的資源。你可能會想複製一個新的視窗,保持所有屬性與原來的視窗相同, 但必須是一個新的對象(因為如果不是新的對象,那麼一個視窗中的改變就會影響到另一個視窗)。還有一種情況: 如果對象A中儲存著對象B的引用,當你複製對象A時,你想其中使用的對象不再是對象B而是B的一個副本,那麼 你必須得到對象A的一個副本。

對象複製可以通過clone關鍵字來完成(如果可能,這將調用對象的__clone()方法)。對象中的 __clone()方法不能被直接調用。

 

Demo 1
<?phpclass Person {    private $name;        private $age;        private $id;        function __construct( $name, $age ) {        $this->name = $name;        $this->age = $age;    }    function setId( $id ) {        $this->id = $id;    }        function __clone() {        $this->id = 0;    }}print "<pre>";$person = new Person( "bob", 44 );$person->setId( 343 );$person2 = clone $person;print_r( $person );print_r( $person2 );print "</pre>";?>
Demo 2
<?phpclass Account {    public $balance;    function __construct( $balance ) {        $this->balance = $balance;    }}class Person {    private $name;    private $age;    private $id;    public $account;    function __construct( $name, $age, Account $account ) {        $this->name = $name;        $this->age  = $age;        $this->account = $account;    }    function setId( $id ) {        $this->id = $id;    }    function __clone() {        $this->id   = 0;    }}$person = new Person( "bob", 44, new Account( 200 ) );$person->setId( 343 );$person2 = clone $person;// give $person some money$person->account->balance += 10;// $person2 sees the credit tooprint $person2->account->balance;// output:// 210?>

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.