2

我以前见过这个问题,但我的特殊情况似乎很奇怪,我无法解决它 - 任何见解都将不胜感激。

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

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

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

$var = 0;

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

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

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

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()

4

1 回答 1

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]};
?>
于 2012-12-06T22:17:48.640 回答