PHP syntax for dereferencing function result

后端 未结 22 1113
不知归路
不知归路 2020-11-22 02:14

Background

In every other programming language I use on a regular basis, it is simple to operate on the return value of a function without declaring

22条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 02:39

    Previously in PHP 5.3 you had to do this:

    function returnArray() {
      return array(1, 2, 3);
    }
    $tmp = returnArray();
    $ssecondElement = $tmp[1];
    

    Result: 2

    As of PHP 5.4 it is possible to dereference an array as follows:

    function returnArray() {
      return array(1, 2, 3);
    }
    $secondElement = returnArray()[1];
    

    Result: 2

    As of PHP 5.5:

    You can even get clever:

    echo [1, 2, 3][1];
    

    Result: 2

    You can also do the same with strings. It's called string dereferencing:

    echo 'PHP'[1];
    

    Result: H

提交回复
热议问题