按变量访问对象属性

时间:2012-12-06 22:13:12

标签: php

我以前见过这个问题,但我的具体案例似乎有些奇怪,我无法解决它 - 任何见解都会受到赞赏。

我正在尝试使用变量值访问对象属性,即

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

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

$var = 0;

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

这会抛出错误“注意:未定义的属性:stdClass :: $ first”。删除大括号会返回相同的结果。

我不明白什么? (下面的实际代码和错误 - 错误是在Drupal Watchdog日志中记录的。)

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;
}
  

注意:未定义的属性:   stdClass :: $ field_portfolio_district ['und'] [0] ['nid'] in   ComparisonChart-> load_questionnaire_queue()

1 个答案:

答案 0 :(得分:0)

这就像一个魅力:

<?php
$foo = new StdClass();
$foo->first = 'bar';

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

$var = 0;

echo $foo->{$array[$var]};
?>

但我怀疑这会起作用:

<?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]};
?>