The use of $tmp
below is pretty ugly. Is there a way to avoid it?
function test()
{
return array('a'=>1, 'b'=>2);
}
$tmp = test();
echo "This should be 2: ", $tmp['b'], "\n";
Is there some reason the natural
test()['b']
doesn't work?
The use of $tmp
below is pretty ugly. Is there a way to avoid it?
function test()
{
return array('a'=>1, 'b'=>2);
}
$tmp = test();
echo "This should be 2: ", $tmp['b'], "\n";
Is there some reason the natural
test()['b']
doesn't work?
After further research I believe the answer is no, a temporary variable like that is indeed the canonical way to deal with an array returned from a function.
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 :(
If it is just aesthetic, then the Object notation will work if you return an object. As far as memory management goes, no temporary copy if made, only a change in reference.
Give it a name that makes sense, even if it's temporary. Call it by what it contains depending on your context.
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. ;)
These are some ways to approach your problem.
First you could use to name variables directly if you return array of variables that are not part of the collection but have separate meaning each.
Other two ways are for returning the result that is a collection of values.
function test() {
return array(1, 2);
}
list($a, $b) = test();
echo "This should be 2: $b\n";
function test2() {
return new ArrayObject(array('a' => 1, 'b' => 2), ArrayObject::ARRAY_AS_PROPS);
}
$tmp2 = test2();
echo "This should be 2: $tmp2->b\n";
function test3() {
return (object) array('a' => 1, 'b' => 2);
}
$tmp3 = test3();
echo "This should be 2: $tmp3->b\n";
You could use references:
$ref =& myFunc();
echo $ref['foo'];
That way, you're not really creating a duplicate of the returned array.
EDIT: apparently, array dereferencing has been added now:
Original Answers:
This has been been asked already before. The answer is no. It is not possible.
To quote Andi Gutmans on this topic:
This is a well known feature request but won't be supported in PHP 5.0. I can't tell you if it'll ever be supported. It requires some research and a lot of thought.
You can also find this request a number of times in the PHP Bugtracker. For technical details, I suggest you check the official RFC and/or ask on PHP Internals.