PHP - 5.4 Array dereferencing 數組值

來源:互聯網
上載者:User

標籤: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 數組值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.