peter300 peter300 - 1 year ago 56
PHP Question

Accessing element from standard class object

I am trying to retrieve a variable in the Drupal Module Viewsphp but my problem is really just accessing nested elements in stdclass object.

print_r($data->node_created); // gives correct value 1477420603

returns nothing should be 31

What am I doing wrong ?

Here is an extract of the data returned:

stdClass Object
[node_title] => Denver
[nid] => 31
**[node_created] => 1477420603**
[field_data_body_node_entity_type] => node
[field_data_field_colour_node_entity_type] => node
[field_data_field_type_node_entity_type] => node
[_field_data] => Array
[nid] => Array
[entity_type] => node
[entity] => stdClass Object
**[vid] => 31**
[uid] => 1
[title] => Denver
[log] =>
[status] => 1
[comment] => 2
[promote] => 1
[sticky] => 0
[nid] => 31
[type] => test1
[language] => und

Answer Source

You are using an object at first use the object operator ->. This is how you access attributes or methods of an object. This will return the value of that operation.

//This is accessing the array stored in _field_data

//Since that is an array now you have to access
//the data in it with the indexes of the array


Notice though that in your output [entity] => stdClass Object entity is back to an object so you need to go back to the ->.

//Full access


Normally objects have accessors or getter methods ie getVid() methods. Not sure if that is the case here but it you could then access data like $data->getVid(); which is a lot simpler and can protect your code down the road if the underlying api changes. Worth looking into the docs or code for.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download