php array selector unsure of differnce
hi I working with Drupal and it uses arra开发者_StackOverflow中文版ys to a level I'm not very familier with, I've a quick question which is what is the difference between these 'selectors'(is that the right term)?
This causes an error "Fatal error: Cannot use object of type stdClass as array in..."
$node['field_geoloc']
this works (im using it in an if != null statement)
$node->field_geoloc
hopefully an easy question... thanks.
Pretty easy.. the error says it all:
"Fatal error: Cannot use object of type stdClass as array in..."
You are attempting to use an object as an array.
Object properties aren't accessibly using the $array['key']
method that you are used to. You need to access properties like:
`$object->property`
If you have an object, you can get the properties from that array by using the get_object_vars method. But I know from experience that you should not use that method with a $node in Drupal.
->
is operator for accessing public object properties (and call public methods). In order for an object properties to be accessed with $object['key']
syntax, it have to implement ArrayAccess. Other option is to cast the object to array ( $node = (array) $node
(but this will work only for first-level keys, e.g. it will turn $node->page
to $node['page']
, but not $node->page->title
to $node['page']['title']
- the later will be accessible via $node['page']->title
Because you can't use object as an array.
That first is an array and that second is an object.
The first one is an array, the second one is an object (of class StdClass). But you may be interested in this interface: http://php.net/manual/en/class.arrayaccess.php which allows accessing an object as an array (so you do $obj['key'] instead of $obj->key)
精彩评论