[英]Adding data to a reference to change the referenced array in PHP
我建立了一個函數來檢索數組的最后一個指定鍵,它引用該數組並顯示得很好,但是,當我嘗試添加到引用變量時,它不會影響引用的數組。
這是我的代碼:
class test {
public function __construct() {
// For testing
$this->keys[] = 'key1';
$this->keys[] = 'key2';
$this->array['key1']['key2'] = 'Hello World';
}
protected function &getArray() {
$array = &$this->array;
foreach($this->keys as $key) {
$array = &$array[$key];
}
return $array;
}
function add() {
$tmpArray = $this->getArray();
print_r($tmpArray);
echo "<br>\n";
$tmpArray = 'Goodbye World';
print_r($tmpArray);
echo "<br>\n";
print_r($this->array);
}
}
$test = new test;
$test->add();
總結起來,add()和__construct()用於測試。 我試圖用add()添加到$this->array
。 但是,當我指定$tmpArray = 'Goodbye World'
,引用的數組$this->array['key1']['key2']
仍然是Hello World。
有人可以幫我指出正確的方向嗎?
為了在PHP中返回引用,您需要使用&
兩次,一次在定義中,一次在賦值中。 您缺少作業中的一個:
$tmpArray = &$this->getArray();
有關詳細信息,請參見PHP:返回參考 。請不要問為什么,因為我無法為PHP行為生成基本原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.