標籤:blog io ar sp div 問題 c on cti
在5.4之前我們直接擷取數組的值得方法如下
<?php $str = ‘a;b;c;d‘; list($value) = explode(‘;‘,$str); echo $value;
結果為: a
但是5.4的Array derenferencing 是什麼意思呢?如下
<?php $str = ‘a;b;c;d‘; $value = explode(‘;‘,$str)[0]; echo $value;
結果同為:a
其實很簡單,但是我們運用當中可能會出現一些的問題。比如
<?php class Example{ private $value = []; public function getValue(){ return $this->value; } } $example = new Example; $example->getValue()[‘test‘] = ‘test‘; echo $example->getValue()[‘test‘];
會出現如下報錯
Notice: Undefined index: test in D:\Php\xampp\htdocs\test\PHP - 5.x\example.php on line 17
上面的代碼混淆了傳回值和返回引用,在PHP中,除非你顯示的指定返回引用,否則對於數組PHP是值返回,也就是數組的拷貝。因此上面代碼對返回數組賦值,實際是對拷貝數組進行賦值,非原數組賦值。
下面是一種可能的解決辦法,輸出拷貝的數組,而不是原數組:
$vals = $config->getValues(); $vals[‘test‘] = ‘test‘; echo $vals[‘test‘]; //test
如果你就是想要改變原數組,也就是要反回數組引用,就是顯示指定返回引用即可
<?php class Example{ private $value = []; public function &getValue(){ return $this->value; } } $example = new Example; $example->getValue()[‘test‘] = ‘test‘; echo $example->getValue()[‘test‘];
上面的例子輸出:test
PHP - 5.4 Array dereferencing 數組值