dongpai2754 2012-12-06 22:13
浏览 68
已采纳

按变量访问对象属性

I've seen this asked before, but my particular case appears to be someone odd, and I'm unable to resolve it - any insight would be appreciated.

I'm trying to access an object property with a variable value, ie.

$foo = new Object();
$foo->first = 'bar';

$array = array(0 =>'first', 1 =>'second');

$var = 0;

return $foo->{$array[$var]};

This is throwing an error "Notice: Undefined property: stdClass::$first". Removing the braces returns an identical result.

What don't I understand? (Actual code and error below - the error is as recorded in a Drupal Watchdog log.)

private function load_questionnaire_queue($type, $comparator_id, $comparing_id_array)
{
  $queue = array();
  $type_map = array(
    0 => "field_portfolio_district['und'][0]['nid']",
    1 => "field_time_period['und'][0]['tid']",
  );

  foreach ($this->questionnaires as $q)
  {

    // The commented code below works as expected
    // if ($q->field_portfolio_district['und'][0]['nid'] == $comparator_id &&
    //      in_array($q->field_time_period['und'][0]['tid'], $comparing_id_array))

    // This returns an identical error, with or without braces:
    if ($q->{$type_map[$type]} == $comparator_id && 
            in_array($q->{$type_map[!$type]}, $comparing_id_array))
    {
      $queue[] = node_view($q, $view_mode = 'full');
    }
  }

  $this->queue = $queue;
}

Notice: Undefined property: stdClass::$field_portfolio_district['und'][0]['nid'] in ComparisonChart->load_questionnaire_queue()

  • 写回答

1条回答 默认 最新

  • dpnw86361 2012-12-06 22:17
    关注

    This works like a charm:

    <?php
    $foo = new StdClass();
    $foo->first = 'bar';
    
    $array = array(0 =>'first', 1 =>'second');
    
    $var = 0;
    
    echo $foo->{$array[$var]};
    ?>
    

    But I doubt this is gonna work:

    <?php
    $foo = new StdClass();
    $foo->first = array('a' => array('b' => 'test'));
    
    $array = array(0 =>'first["a"]["b"]', 1 =>'second');
    
    $var = 0;
    
    echo $foo->{$array[$var]};
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题