2010-03-09 83 views
1

任何人都可以向我解釋爲什麼以下是導致語法錯誤(意外'=')?PHP語法錯誤

protected function processDates() 
    { 
     foreach($this->dates as $name => $unitprefix)  
     { 
      $this->$unitprefix.'year' = ''; 
      $this->$unitprefix.'month' = ''; 
      $this->$unitprefix.'day' = ''; 
     } 
    } 

顯然我不會把這些值留空,但在繼續之前,我需要修復當前的問題。

任何意見讚賞。

謝謝。

回答

8

嘗試

$this->${$unitprefix.'year'} = ''; 

但是要提供更好的提醒這將是很好的瞭解你的類的屬性,什麼$unitprefix包含。

參考:Variable variables

透露更多的細節:
您的代碼是不明確的解析器在你寫的方式。假設$unitprefix = 'foo',你的代碼可以從兩個方面來解釋:

  1. 獲取的$this->$unitprefix值,即$this->foo和追加'year'。然後,您的代碼會導致(與$this->foo = bar):

    'baryear' = '';
    我猜這是什麼解析器是做,因爲這相當於代碼的評估由左到右。

  2. 追加'year'$unitprefix並用所得的名字獲得產權,即所產生的代碼是:

    $this->fooyear = '';

二是你想擁有的beviour但沒有${}解析器不知道該怎麼做。

+0

感謝您的幫助。 – Dan 2010-03-09 16:38:42