PHP對(duì)象克隆clone用法示例
本文實(shí)例講述了PHP對(duì)象克隆clone用法。分享給大家供大家參考,具體如下:
淺克?。?/strong>只是克隆對(duì)象中的非對(duì)象非資源數(shù)據(jù),即對(duì)象中屬性存儲(chǔ)的是對(duì)象類型,則會(huì)出現(xiàn)克隆不完全
<?php
class B{
public $val = 10;
}
class A{
public $val = 20;
public $b;
public function __construct(){
$this->b = new B();
}
}
$obj_a = new A();
$obj_b = clone $obj_a;
$obj_a->val = 30;
$obj_a->b->val = 40;
var_dump($obj_a);
echo '<br>';
var_dump($obj_b);
運(yùn)行結(jié)果如下:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[2] public 'val' => int 40
深克?。?/strong>一個(gè)對(duì)象的所有屬性數(shù)據(jù)都徹底的復(fù)制,需要使用魔術(shù)方法__clone(),并在里面實(shí)現(xiàn)深度克隆
<?php
class B{
public $val = 10;
}
class A{
public $val = 20;
public $b;
public function __construct(){
$this->b = new B();
}
public function __clone(){
$this->b = clone $this->b;
}
}
$obj_a = new A();
$obj_b = clone $obj_a;
$obj_a->val = 30;
$obj_a->b->val = 40;
var_dump($obj_a);
echo '<br>';
var_dump($obj_b);
運(yùn)行結(jié)果如下:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[4] public 'val' => int 10
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP基本語(yǔ)法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
- php面向?qū)ο笕ヂ?(三)特殊的引用“$this”的使用
- PHP對(duì)象遞歸引用造成內(nèi)存泄漏分析
- PHP對(duì)象相互引用的內(nèi)存溢出實(shí)例分析
- php中引用&的用法分析【變量引用,函數(shù)引用,對(duì)象引用】
- php5對(duì)象復(fù)制、clone、淺復(fù)制與深復(fù)制實(shí)例詳解
- PHP對(duì)象的淺復(fù)制與深復(fù)制的實(shí)例詳解
- PHP動(dòng)態(tài)地創(chuàng)建屬性和方法, 對(duì)象的復(fù)制, 對(duì)象的比較,加載指定的文件,自動(dòng)加載類文件,命名空間
- PHP 5.0對(duì)象模型深度探索之對(duì)象復(fù)制
- php面向?qū)ο笕ヂ?(十一)__toString()用法 克隆對(duì)象 __call處理調(diào)用錯(cuò)誤
- php實(shí)現(xiàn)對(duì)象克隆的方法
- PHP面向?qū)ο蟪绦蛟O(shè)計(jì)高級(jí)特性詳解(接口,繼承,抽象類,析構(gòu),克隆等)
- php中對(duì)象引用和復(fù)制實(shí)例分析
相關(guān)文章
屏蔽PHP默認(rèn)設(shè)置中的Notice警告的方法
很多時(shí)候其實(shí)寫出來(lái)的代碼的錯(cuò)誤可以忽略或者根本就不是錯(cuò)誤,PHP還是會(huì)顯示Notice警告,well接下來(lái)我們就來(lái)介紹一下屏蔽PHP默認(rèn)設(shè)置中的Notice警告的方法2016-05-05
PHP中l(wèi)trim()函數(shù)的用法與實(shí)例講解
今天小編就為大家分享一篇關(guān)于PHP中l(wèi)trim()函數(shù)的用法與實(shí)例講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03
微信 開發(fā)生成帶參數(shù)的二維碼的實(shí)例
這篇文章主要介紹了微信 開發(fā)生成帶參數(shù)的二維碼的實(shí)例的相關(guān)資料,這里詳細(xì)介紹該如何實(shí)現(xiàn)二維碼,需要的朋友可以參考下2016-11-11
php簡(jiǎn)單實(shí)現(xiàn)多維數(shù)組排序的方法
這篇文章主要介紹了php簡(jiǎn)單實(shí)現(xiàn)多維數(shù)組排序的方法,涉及php數(shù)組的遍歷及array_multisort函數(shù)的相關(guān)使用技巧,需要的朋友可以參考下2016-09-09
PHP實(shí)現(xiàn)的鏈?zhǔn)疥?duì)列結(jié)構(gòu)示例
這篇文章主要介紹了PHP實(shí)現(xiàn)的鏈?zhǔn)疥?duì)列結(jié)構(gòu),結(jié)合具體實(shí)例形式分析了php鏈?zhǔn)疥?duì)列的定義及入隊(duì)、出隊(duì)、打印隊(duì)列等基本操作實(shí)現(xiàn)與使用方法,需要的朋友可以參考下2017-09-09

