如何在沒有引用的情況下複製物件?
P粉805922437
P粉805922437 2023-08-24 10:51:49
0
2
382
<p>有據可查,PHP5 OOP 物件預設透過引用傳遞。如果這是預設的,在我看來,有一種非預設的方式可以在沒有參考的情況下進行複製,那麼如何? ? </p> <pre class="brush:php;toolbar:false;">function refObj($object){ foreach($object as &$o){ $o = 'this will change to ' . $o; } return $object; } $obj = new StdClass; $obj->x = 'x'; $obj->y = 'y'; $x = $obj; print_r($x) // object(stdClass)#1 (3) { // ["x"]=> string(1) "x" // ["y"]=> string(1) "y" // } // $obj = refObj($obj); // no need to do this because refObj($obj); // $obj is passed by reference print_r($x) // object(stdClass)#1 (3) { // ["x"]=> string(1) "this will change to x" // ["y"]=> string(1) "this will change to y" // }</pre> <p>此時我希望 <code>$x</code> 成為原始的 <code>$obj</code>,但當然不是。有什麼簡單的方法可以做到這一點還是我必須寫類似的程式碼</p>
P粉805922437
P粉805922437

全部回覆(2)
P粉038161873

要複製對象,您需要使用對象克隆一个>.

要在您的範例中執行此操作,請執行以下操作:

$x = clone $obj;

請注意,物件可以使用 __clone() 定義自己的克隆行為,這可能會給您帶來意想不到的行為,因此請記住這一點。

P粉713846879
<?php
$x = clone($obj);

所以它應該是這樣的:

<?php
function refObj($object){
    foreach($object as &$o){
        $o = 'this will change to ' . $o;
    }

    return $object;
}

$obj = new StdClass;
$obj->x = 'x';
$obj->y = 'y';

$x = clone($obj);

print_r($x)

refObj($obj); // $obj is passed by reference

print_r($x)
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!