2012-12-06 182 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

我當時太想。我會重構。 –