PHP retrieving array values using dash arrow “->”

2019-04-03 13:09发布

问题:

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:

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?

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 :(

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

回答1:

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.

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.



回答2:

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.

You can reading more about objects on this page of the PHP manual.



回答3:

Those aren't arrays, they're objects.



回答4:

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'