2012-01-08 103 views
-3

這是IF語句。我想稍後訪問timeStampCleaned變量。爲什麼我不能訪問If語句中的變量?

if ($xmlRatesTime = '') { 
     $timeStampCleaned = date('j F Y H:i', $ratesTimeStamp); // Convert unix timestamp into date format 
    } else { 
     // ... 
    } 

像這樣:

if(empty($ratesTimeStamp)) { 

     $newXML = simplexml_load_file('cache/rates.xml'); 

     $child = $newXML->addChild('currency'); 
     $child->addAttribute('id', ''.$to.''); 
     $child->addChild('title', $toTitle); 
     $child->addChild('loc', $toLocation); 
     $child->addChild('rate', $finalRate); 
     $child->addChild('timestamp', $timeStamp); 

     $dom = new DOMDocument('1.0'); 
     $dom->preserveWhiteSpace = false; 
     $dom->formatOutput = true; 
     $dom->loadXML($newXML->asXML()); 
     $newXMLdomCleaned = $dom->saveXML(); 

     file_put_contents('cache/rates.xml', $newXMLdomCleaned); 
    } 

但我得到的錯誤:

Notice: Undefined variable: timeStampCleaned in ...file... on line 208 

從我的理解,如果報表是精細內訪問變量。所以我不知道爲什麼這不起作用!?

感謝

+1

製作一個測試用例。 – 2012-01-08 19:50:13

+0

你在哪裏試圖獲得'timeStampCleaned'變量?不在你粘貼的代碼中。 – 2012-01-08 19:52:46

+2

IF語句是有條件的,所以如果你第一次使用這個變量在你的IF語句中(即在那裏定義),那麼你必須確保它被實際調用。如果你的IF語句跳過它,當你稍後使用它時,它將是未定義的。 – 2012-01-08 19:53:12

回答

2

這可能是因爲你沒有在聲明else部分聲明變量。如果除非$xmlRatesTime等於'',則不會創建$timeStampCleaned。嘗試在「else」中添加一個聲明,例如:

if ($xmlRatesTime = '') { 
    $timeStampCleaned = date('j F Y H:i', $ratesTimeStamp); 
} else { 
    $timeStampCleaned = ''; // add this here! 
} 

雖然,一般來說,我覺得這是不好的編程習慣。我會建議在聲明變量之前 if語句完全,如:

$timeStampCleaned = ''; 
if ($xmlRatesTime = '') { 
    $timeStampCleaned = date('j F Y H:i', $ratesTimeStamp); 
} else { 
    //whatever 
} 

作爲一個側面說明,你的意思是$xmlRatesTime==''(兩個等號)?

+1

謝謝。這是解決它:)(是的,我確實意味着==以及糟糕!) – tctc91 2012-01-08 20:00:08

+0

,如果你不介意這標誌着作爲解決,它會幫助我;) – cegfault 2012-01-08 20:08:22

+0

有它會前發佈後等待幾分鐘讓我解決。再次感謝:) – tctc91 2012-01-08 20:20:06

1

1)讀了更多的變量範圍(我不是一個PHP的人,但我花了幾秒鐘挖這件事:http://php.net/manual/en/language.variables.scope.php

2)平等的測試,你以爲你在做根本不是平等測試。使用=====

+0

變量範圍_might可能是這裏的一個問題,但不能用提供的信息告知(他沒有說代碼在函數內部) – 2012-01-08 19:58:20

相關問題