将函数的返回值直接解释为数组 [英] Interpreting return value of function directly as an array

查看:123
本文介绍了将函数的返回值直接解释为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否有一种方法可以将函数的返回值直接解释为数组?

Is there a way in PHP to interpret the return value of a function directly as an array?

让我说我有一个功能:

function getArray()  {
  return array("foo", "bar");
}

代替写作:

$array = getArray();
$var = $array[1];

我想像这样直接访问栏":

i want to access "bar" directly somewhat like:

$var = getArray()[1]; //this causes an error

推荐答案

您想要的东西称为数组取消引用,并且仅在PHP 5.4(即将发布的PHP版本)中受支持.

What you want is called array dereferencing and will be supported only as of PHP 5.4 (which is the upcoming PHP version).

现在,您可以使用 list 语言构造:

For now you can use the list language construct:

list(, $var) = getArray();

如果您需要将该值传递给其他函数,则仍然可以解决该限制(这仅供参考,而不是您应使用的):

If you need the value to pass it to some other function, you can still hack around the limitation (this is just for reference, not something you should use):

func(${'_'.!$_=getArray()}[1]); // using the $_ var
func(${!${''}=getArray()}[1]);  // using the $ var

这篇关于将函数的返回值直接解释为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆