2012-12-06 276 views
2

我以前见过这个问题,但我的具体案例似乎有点奇怪,我无法解决它 - 任何洞察力将不胜感激。通过变量访问对象属性

我想访问一个变量值的对象属性,即。

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

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

$var = 0; 

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

这是抛出一个错误 “通知:未定义的属性:stdClass的:: $第一”。去除大括号将返回相同的结果。

我不明白什么? (下面的实际代码和错误 - 错误被记录在一个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 “在 ComparisonChart-> load_questionnaire_queue()

回答

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

你确实有一点...... thx。 –

+0

这里的解决方案是eval(),但我强烈建议你不要使用eval或这样的方法。 –

+0

我当时太想。我会重构。 –