开发者

Can an element of an array return by a function be used without prior assignment?

开发者 https://www.devze.com 2023-02-21 12:00 出处:网络
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 fi

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. ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消