为什么不能在函数的返回值上使用数组索引? [英] Why can't I use an array index on the return value of a function?

查看:127
本文介绍了为什么不能在函数的返回值上使用数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为什么不能这样做?

explode(',','1,2,3', 1)[0]

其他所有语言都支持它.

Every other language supports it.

我正在寻找的答案:(因为人们似乎认为这是毫无意义的咆哮)

Answers I'm looking for: (since people seem to think this is a pointless rant)

应该让我知道的变量和返回值的行为之间有某种区别吗?

Is there some sort of a difference between how a variable and a return value behaves that I should be made aware of?

这是设计决定吗?他们只是懒惰吗?语言的构建方式是否存在某种使它难以实施的东西?

Was this a design decision? Were they just lazy? Is there something about the way the language was built that makes this exceedingly difficult to implement?

推荐答案

我为什么不能这样做?

Why can't I do this?

因为PHP当前不支持此语法.但是您可以将其传递给函数,例如:

Because PHP doesn't currently support this syntax. But you can pass it to a function, e.g.:

current(explode(',','1,2,3', 1));

否则,您必须先将返回值分配给变量,然后再通过索引进行访问.

Otherwise, you have to assign the return value to a variable first, then access via index.

更多信息:

因此可以链接方法调用或 属性访问.现在很久了 人们要求相同的东西 数组偏移量访问. 这通常是 由于不确定因素而被拒绝 内存问题,因为我们不喜欢 内存泄漏.但是经过适当的 评估Felipe提交了补丁 这样您就可以执行以下操作:

So one can chain method calls or property access. Now for a long time people requested the same thing for array offset access. This was often rejected due to uncertainties about memory issues, as we don't like memory leaks. But after proper evaluation Felipe committed the patch which allows you to do things like:

function foo() {
    return array(1, 2, 3);
}
echo foo()[2]; // prints 3

http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html

因此,它处于开发管道中,但正如我所说,目前不受支持.

So, it is in the development pipeline but, as I stated, is not currently supported.

PHP> = 5.4 现在支持函数数组取消引用,例如foo()[0]

PHP >= 5.4 now supports function array dereferencing, e.g. foo()[0]

这篇关于为什么不能在函数的返回值上使用数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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