PHP syntax for dereferencing function result

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

    As others have mentioned, this isn't possible. PHP's syntax doesn't allow it. However, I do have one suggestion that attacks the problem from the other direction.

    If you're in control of the getBarArray method and have access to the PHP Standard Library (installed on many PHP 5.2.X hosts and installed by default with PHP 5.3) you should consider returning an ArrayObject instead of a native PHP array/collection. ArrayObjects have an offetGet method, which can be used to retrieve any index, so your code might look something like

    append('dos');
            $array->append('tres');
            return $array;
        }
    }
    
    $foo = new Example();
    $value = $foo->getBarArray()->offsetGet(2);
    

    And if you ever need a native array/collection, you can always cast the results.

    //if you need 
    $array = (array) $foo->getBarArray();
    

提交回复
热议问题