PHP物件導向之複製

來源:互聯網
上載者:User

php4物件導向最大的缺點之一,是將對象視為另一種資料類型,這使得很多常見的OOP方法無法使用,如設計模式。這些OOP方法依賴於將對象作為引用傳遞給其他的類的方法,而不是作為值傳遞。幸好PHP解決了這個問題。現在所有對象在預設情況下都被視為引用。但是因為所有對象對被視為引用而不是值,所以現在複製對象顯得更難了。如果嘗試複製一個對象,這是會指向原對象的地址。為瞭解決複製問題,PHP提供了一種複製顯示對象的方法。

執行個體如下:

首先介紹使用clone關鍵字複製對象:

name = $na;    }        function getName()    {    return $this->name;    }        function setNum($nu)    {    $this->num = $nu;    }    function getNum()    {    return $this->num;    }    }        $test = new TestClone();    $test->setName("tianxin");    $test->setNum(123456);    echo $test->getName();    echo $test->getNum()."";        $test2 = clone $test;    $test2->setName("liwei");    echo $test->getName();    echo $test->getNum()."";        echo $test2->getName();    echo $test2->getNum();    ?>
運行結果:
tian123456tian123456xia123456

從運行結果中我們看到,如果test2不對name進行修改。test與test2這兩個對象的雖然是不同的對象但是卻有相同的屬性,而且改變test2對象的屬性並不會影響test對象的屬性,因此可以斷定複製是傳值,而不是簡單的引用。

PHP5定義了一個特殊的方法名“__clone()”方法,是在對象複製時自動調用的方法,用“__clone()”方法將建立一個與原對象擁有相同屬性和方法的對象,如果想在複製後改變原對象的內容,需要在__clone()中重寫原本的屬性和方法, ”__clone()”方法可以沒有參數,它自動包含$this和$that兩個指標,$this指向複本,而$that指向原本

name = $na;    }        function getName()    {    return $this->name;    }        function setNum($nu)    {    $this->num = $nu;    }    function getNum()    {    return $this->num;    }        function __clone()    {    $this->name = "huang";    }    }        $test = new TestClone();    $test->setName("tian");    $test->setNum(123456);    echo $test->getName();    echo $test->getNum()."";        $test2 = clone $test;//     $test2->setName("xia");    echo $test->getName();    echo $test->getNum()."";        echo $test2->getName();    echo $test2->getNum();    ?>

運行結果:
tian123456tian123456huang123456

name = $name;        $this->sex = $sex;        $this->age = $age;    }    // 這個人可以說話的方法, 說出自己的屬性    function say() {        echo "我的名字叫:" . $this->name . " 性別:" . $this->sex . " 我的年齡是:" . $this        ->age . "";    }    // 對象複製時自動調用的方法, 如果想在複製後改變原對象的內容,需要在__clone()中重寫原來的屬性和方法。    function __clone() {        // $this 指的複本p2, 而$that 是指向原本p1,這樣就在本方法裡,改變了複本的屬性。        $this->name = "我是複製的張三$that->name";        // $this->age = 30;    }}$p1 = new Person ( "張三", "男", 20 );$p2 = clone $p1;$p1->say ();$p2->say ();?>

運行後的結果:

我的名字叫:張三 性別:男 我的年齡是:20我的名字叫:我是複製的張三 性別:男 我的年齡是:20



聯繫我們

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