2010-07-21 16 views
4
<h1><?php echo $GLOBALS['translate']['About'] ?></h1> 
Notice: Undefined index: About in page.html on line 19 

是否可以「捕捉」一個未定義的索引,這樣我可以創建它(數據庫查詢)&從我的函數返回後再執行回聲?抓住未定義指數創建

回答

0

是的。使用isset來確定索引是否已定義,如果不是,則可以爲其分配一個值。

if(!isset($GLOBALS['translate']['About'])) { 
    $GLOBALS['translate']['About'] = 'foo'; 
    } 
echo "<h1>" . $GLOBALS['translate']['About'] . "</h1>"; 
+3

這是一個很草率的帖子:一個假')',缺少';',缺少打開/關閉標籤... – mvds 2010-07-21 10:54:52

+1

......這確實很糟糕。謝謝你的收穫。 – 2010-07-21 11:15:44

0

嘗試類似:

if (!isset($GLOBALS['translate']['About'])) 
{ 
    $GLOBALS['translate']['About'] = get_the_data('About'); 
} 
echo $GLOBALS['translate']['About']; 
7

最簡單的方法來檢查是否已分配的值是使用isset方法:

if(!isset($GLOBALS['translate']['About'])) { 
    $GLOBALS['translate']['About'] = "Assigned"; 
} 
echo $GLOBALS['translate']['About']; 
1

那會不會是正確的要做的事。我會努力正確地構建陣列。否則你最終可能會產生每頁1000分貝的請求。

也,你應該檢查輸出前陣,也許把默認值有:

<h1><?php echo isset($GLOBALS['translate']['About'])?$GLOBALS['translate']['About']:'default'; ?></h1> 
2

您可以檢查,如果你訪問它之前就存在這種特殊的指數。請參閱isset()上的手冊。這是有點笨拙,因爲你必須寫兩次變量名。

if(isset($GLOBALS['translate']['About'])) 
    echo $GLOBALS['translate']['About']; 

您可能還會考慮更改生產環境的error_reporting值。

0

您需要定義您的自定義錯誤處理程序,如果你想趕上未定義指數

set_error_handler('exceptions_error_handler'); 

function exceptions_error_handler($severity, $message, $filename, $lineno) { 
    if (error_reporting() == 0) { 
    return; 
    } 
    if (error_reporting() & $severity) { 
    throw new ErrorException($message, 0, $severity, $filename, $lineno); 
    } 
} 
try{ 
}catch(Exception $e){ 
echo "message error"; 
}