PHP使用破折号“-”检索数组值。 [英] PHP retrieving array values using dash arrow "->"

查看:85
本文介绍了PHP使用破折号“-”检索数组值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用PHP已有一段时间了,但从未成为高级程序员。我觉得这是一个愚蠢的问题,但从未理解为什么可以使用不同的方法检索某些数组值:

I've been using PHP quite a while now, but never been an advanced programmer. I feel like this is dumb question but never understood why some array values can be retrieved using different methods:

此:

$array->value

而不是正常:

$array['value']

标准$ array ['value']始终有效,但使用->方法的标准有时不起作用。为什么?

The standard $array['value'] always works, but the one using the -> method doesn't at times. Why is that?

这里有个例子。我使用的是Zend Framework 2,可以使用->方法获取会话值:

Here's an example. I am using Zend Framework 2 and I can grab a session value using the -> method:

$this->session->some_value

但是,如果执行新的常规数组,我将无法执行:

However, I can't if I do a new, normal array:

$array = array('some_value' => 'myvalue');
$array['some_value']; // works!!
$array->some_value;  // does not work :(

在Zend Framework 1中,大多数数组都可以用这种方式工作,并且在ZF2越来越多,我遇到了需要改变获取价值的方式的问题。
这有意义吗?我肯定会有所帮助。
谢谢,
Greg

In Zend Framework 1 most arrays would work fine this way, and in ZF2 more and more , I run into issues where I need to change the way I get that value. Does this make sense? I sure appreciate any help. Thanks, Greg

推荐答案

如其他答案中所述,使用-> 表示您正在访问一个对象而不是一个数组。

As stated before in other answers, using -> means you are accessing an object, not an array.

但是,有时可能会将一个对象视为一个数组,这是在实现 ArrayAccess 接口。编码人员可以执行此操作例如,调用 $ object-> field 等效于 $ object ['field'] ,但是他/ p不能。

However, it is sometimes possible that an object would be treated as an array. It is when it is implementing ArrayAccess interface. The coder can do such that eg. calling $object->field would be equivalent to $object['field'], but he/she must not.

此外,可以将数组视为对象(请参考使用手册),但是在这种情况下,它不是数组而是对象,与上面的方法相同。

Moreover, it is possible to treat an array as an object (refer to the manual), however in this case it is not an array but an object and is the same way as above.

这篇关于PHP使用破折号“-”检索数组值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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