PHP syntax for dereferencing function result

后端 未结 22 1118
不知归路
不知归路 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 03:02

    There are three ways to do the same thing:

    1. As Chacha102 says, use a function to return the index value:

      function get($from, $id){
          return $from[$id];
      }
      

      Then, you can use:

      get($foo->getBarArray(),0);
      

      to obtain the first element and so on.

    2. A lazy way using current and array_slice:

      $first = current(array_slice($foo->getBarArray(),0,1));
      $second = current(array_slice($foo->getBarArray(),1,1));
      
    3. Using the same function to return both, the array and the value:

      class FooClass {
          function getBarArray($id = NULL) {
              $array = array();
      
              // Do something to get $array contents
      
              if(is_null($id))
                  return $array;
              else
                  return $array[$id];
              }
      }
      

      Then you can obtain the entire array and a single array item.

      $array = $foo->getBarArray();
      

      or

      $first_item = $foo->getBarArray(0);
      

提交回复
热议问题