2012-11-05 48 views
0

在我的父文件的函數內,我從外部的php文件調用一個函數。這是我(簡化)代碼:爲什麼我在外部文件功能中遇到可變範圍問題?

父文件:

$text = ""; 

function htmlify($text, $format){ 

    if (is_array($_POST)) { 
      $html = ($_POST['text']); 
     } else { 
      $html = $text; 
     };  

     $html = str_replace("‘", "'", $html); //Stripping out stubborn MSWord curly quotes 
     $html = str_replace("’", "'", $html); 
     $html = str_replace("」", '"', $html); 
     $html = str_replace("「", '"', $html); 
     $html = str_replace("–", "-", $html); 
     $html = str_replace("…", "...", $html); 



     if ($format == "code"){ 

     $html = str_replace(chr(149), "•",$html); 
     $html = str_replace(chr(150), "—",$html); 
     $html = str_replace(chr(151), "—",$html); 
     $html = str_replace(chr(153), "™",$html); 
     $html = str_replace(chr(169), "©",$html); 
     $html = str_replace(chr(174), "®",$html); 


     $trans = get_html_translation_table(HTML_ENTITIES); 
     $html = strtr($html, $trans); 

     $html = nl2br($html); 
     $html = str_replace("<br />", "<br>",$html); 

     $html = preg_replace ("/(\s*<br>)/", "\n<br>", $html); // seperate lines for each <br> 
     //$text = str_replace ("&amp;#", "&#", $text); 
     //return htmlspecialchars(stripslashes($text), ENT_QUOTES, "UTF-8"); 

     return htmlspecialchars($html, ENT_QUOTES, "UTF-8"); 
     } 
     else if ($format == "clean"){ 
     return $html; 
     } 

}; 

,我發現了以下錯誤:

通知與調用的函數

include "HelperFiles/htmlify.php"; 

function funcName(){ 
    $description = "some sample text"; 
    $description = htmlify($description, "code"); 

    echo $description; 
}; 
funcName(); 

htmlify.php文件:未定義的索引:C:_Localhost_Tools \ HelperFiles \ htmlify.php中的文本25行

I我試圖在多個地方聲明內部和外部的$ text變量,但似乎無法繞過這個錯誤(警告)。任何幫助將不勝感激!謝謝。

回答

2

if (isset($_POST['text'])) { 

更換

if (is_array($_POST)) { 

,你不應該得到警告了。

但是,我會建議刪除這一切。應始終使用函數參數 - 其他所有內容都是令人困惑的。

而且你也可以移除htmlify.php中的第一行 - 基本上什麼都不做。

+0

對不起,應該提到這個函數已經存在,並且使用另一個父文件,它有一個表單在其中。即使當我完全刪除if語句,它仍然有相同的錯誤 – John

+0

好吧,刪除它後切換到未定義的變量$ html,然後我不得不聲明。所以它確實有效。 – John

0

錯誤消息讀取未定義指數,不未定義可變。看看你想要訪問關聯變量的所有地方,text作爲關鍵字,$_POST['text']在我看來是你最好的選擇,沒有任何暗示你處理的是$_POST數據AFAIK ...