Can an element of an array return by a function be used without prior assignment?
I have a function returning an array:
function foo(){ return array('foo'=>1,'bar'=>2); }
Can I access an element of the return array without assigning it to a temporary varia开发者_开发问答ble first (e.g. foo()['bar']
)?
The following example returning an object works like a charm:
function foo(){ return (object) array('foo'=>1,'bar'=>2); }
echo foo()->bar;
No, unfortunately PHP's grammar doesn't allow this. There is no good reason for this btw (there are a few discussions about it on PHP mailinglists).
- PHP: Access Array Value on the Fly
- http://wiki.php.net/rfc/functionarraydereferencing [currently down - Google Cache]
If you really want it, you could consider switching to Python - it not only supports inline access to returned arrays but also many other nice things. ;)
精彩评论