我有一個包含以下一類:PHP返回參考陣列中的其他類
class TestClass {
protected $items = [];
public function toArray(){
return $this->items;
}
// Items gets set using set(array $items){}
}
在另一類我稱之爲:
$tmpList = $list->toArray();
現在,如果我沒有記錯的話,這將創建一個全新的獨立數組,如果TestClass
中的數組有100k個項目,則調用toArray()
將創建另一個數組,其中包含另外100k個項目,用於兩個數組,總計200k個項目。
有沒有辦法讓我只返回TestClass
中的條目的引用,所以我有一個100k條目的數組,而$tmpList
只是引用這些條目?
如果我這樣做是爲了排序的數組,數組不會改變
$tmpList = $list->toArray();
usort($tmpList, function($a, $b) use ($orderBy, $direction){
if($direction == 'desc'){
return $b->$orderBy > $a->$orderBy;
}elseif($direction == 'asc'){
return $b->$orderBy < $a->$orderBy;
}
});
如果我追加此之後:
$list->set($tmpList);
的數組被排序。
*表示*在PHP中與「內存優化」非常不同。 **不要使用這個,除非你的意思是允許兩個獨立的範圍_manipulate_相同的值。** – deceze
我做了一個函數'protected function&arrayRef(){return $ this-> items;}'這個函數基本上做了同樣的事情,但是將它作爲參考返回並且使用了你的賦值方法。 –
@GetOffMyLawn不要抱怨我,當你得到意想不到的副作用,但看到內存消耗沒有真正的區別... – deceze