PHP object property notation

人盡茶涼 提交于 2019-12-25 01:29:40

问题


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
  • dsm() is Drupal developer function for debug printing variables, objects and arrays.

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


回答1:


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.



来源:https://stackoverflow.com/questions/23196959/php-object-property-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!