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
my usual workaround is to have a generic function like this
function e($a, $key, $def = null) { return isset($a[$key]) ? $a[$key] : $def; }
and then
echo e(someFunc(), 'key');
as a bonus, this also avoids 'undefined index' warning when you don't need it.
As to reasons why foo()[x]
doesn't work, the answer is quite impolite and isn't going to be published here. ;)
You could, of course, return an object instead of an array and access it this way:
echo "This should be 2: " . test()->b ."\n";
But I didn't find a possibility to do this with an array :(
There are three ways to do the same thing:
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.
A lazy way using current and array_slice:
$first = current(array_slice($foo->getBarArray(),0,1));
$second = current(array_slice($foo->getBarArray(),1,1));
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);
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
<?php
class Example {
function getBarArray() {
$array = new ArrayObject();
$array[] = 'uno';
$array->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();