这是IF声明。我想稍后访问timeStampCleaned变量。
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
据我所知,访问if语句中的变量很好。所以我不知道为什么这不起作用!?
由于
答案 0 :(得分: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 :(得分:1)
1)阅读更多关于变量范围的内容(我不是一个PHP人员,但我花了几秒钟来挖掘它:http://php.net/manual/en/language.variables.scope.php)
2)你认为你正在做的平等测试根本不是一个平等测试。使用==
或===