【问题标题】:Why am I having issues with variable scope in an external file function?为什么我在外部文件函数中遇到变量范围问题?
【发布时间】:2012-10-25 17:30:35
【问题描述】:

在父文件的函数中,我从外部 php 文件调用函数。这是我的(简化的)代码:

父文件:

include "HelperFiles/htmlify.php";

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

    echo $description;
};
funcName();

带有被调用函数的htmlify.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;
      }

};

我收到以下错误:

注意:未定义索引:第 25 行 C:_Localhost_Tools\HelperFiles\htmlify.php 中的文本

我尝试在多个位置声明范围内外的 $text 变量,但似乎无法绕过此错误(警告)。任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: php function variables include scope


    【解决方案1】:

    错误消息显示为 undefined Index,而不是 undefined variable。查看您尝试访问以text 为键的关联变量的所有地方,在我看来$_POST['text'] 是您最好的选择,没有任何迹象表明您正在处理$_POST 数据AFAIK。 ..

    【讨论】:

      【解决方案2】:

      替换

      if (is_array($_POST)) {
      

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

      你不应该再收到警告了。

      但是,我建议将其全部删除。应始终使用函数参数 - 其他一切都令人困惑。

      您还可以删除 htmlify.php 中的第一行 - 这基本上什么都不做。

      【讨论】:

      • 对不起,应该提到这个功能已经存在并且适用于使用另一个父文件的表单,其中包含一个表单。即使我完全删除了 if 语句,它仍然有同样的错误
      • 好的,删除它后确实切换到未定义的变量 $html 然后我必须声明它。所以它确实有效。
      猜你喜欢
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多