Dmytro Sukhovoy
Dmytro Sukhovoy

Reputation: 992

PHP object property notation

I suddenly stuck here:

  $source = (object) array(
      'field_phone' => array(
          'und' => array(
              '0' => array(
                  'value' => '000-555-55-55',
              ),
          ),
      ),
  );

  dsm($source);
  $source_field = "field_phone['und'][0]['value']";
  dsm($source->{$source_field});                    //This notation doesn't work
  dsm($source->field_phone['und'][0]['value']);     //This does

Why $source object doesn't understand $obj->{$variable} notation? Notice: Undefined property: stdClass::$field_phone['und']['0']['value']

Upvotes: 0

Views: 1574

Answers (1)

deceze
deceze

Reputation: 522135

Because your object does not have a property that is named "field_phone['und'][0]['value']". It has a property that is named "field_phone" which is an array which has an index named "und" which is an array which has an index 0 and so on. But the notation $obj->{$var} does not parse and recursively resolve the name, as it shouldn't. It just looks for the property of the given name on the given object, nothing more. It's not like copy and pasting source code in place of $var there.

Upvotes: 2

Related Questions