PHP 使用虚线箭头“->”检索数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16629371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP retrieving array values using dash arrow "->"
提问by gregthegeek
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:
我使用 PHP 已经有一段时间了,但从来没有成为高级程序员。我觉得这是一个愚蠢的问题,但从未理解为什么可以使用不同的方法检索某些数组值:
This:
这个:
$array->value
rather than normal:
而不是正常:
$array['value']
The standard $array['value'] always works, but the one using the -> method doesn't at times. Why is that?
标准的 $array['value'] 始终有效,但使用 -> 方法的方法有时无效。这是为什么?
Here's an example. I am using Zend Framework 2 and I can grab a session value using the -> method:
这是一个例子。我正在使用 Zend Framework 2,我可以使用 -> 方法获取会话值:
$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 :(
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
在 Zend Framework 1 中,大多数数组都可以通过这种方式正常工作,并且在 ZF2 中越来越多,我遇到了需要更改获取该值的方式的问题。这有意义吗?我当然感谢任何帮助。谢谢,格雷格
采纳答案by Voitcus
As stated before in other answers, using ->
means you are accessing an object, not an array.
正如之前在其他答案中所述,使用->
意味着您正在访问一个对象,而不是一个数组。
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.
但是,有时可能会将对象视为数组。它是在实现ArrayAccess
接口的时候。编码器可以这样做,例如。呼叫$object->field
将等同于$object['field']
,但他/她不能。
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.
此外,可以将数组视为对象(请参阅手册),但在这种情况下,它不是数组而是对象,与上述方法相同。
回答by rpkamp
The variables that allow you get properties with ->
are actually objects, not arrays. They do allow the ['some_key']
syntax, but that doesn't mean they are arrays. They are not.
允许您获取属性的变量->
实际上是对象,而不是数组。它们确实允许使用['some_key']
语法,但这并不意味着它们是数组。他们不是。
You can reading more about objects on this page of the PHP manual.
您可以在 PHP 手册的这个页面上阅读更多关于对象的信息。
回答by Kevin Choppin
That is because it is not an array it is an objects variable.
那是因为它不是数组,而是对象变量。
For example;
例如;
class MyObject{
var $myVariable = 'test';
}
$MyObject = new MyObject();
echo $MyObject->myVariable; // Would return 'test'