【问题标题】:Notice: Undefined variable: var1 in \www\test.php on line 7 [duplicate]注意:未定义的变量:第 7 行 \www\test.php 中的 var1 [重复]
【发布时间】:2012-06-26 03:02:36
【问题描述】:

可能重复:
How to use include within a function?

我有两个文件

inc.php 文件

<?php
$var1 = "foo";
$var1 .= "bar";
?>

test.php 文件

<?php
function getcontent($file) {
 include ($file);
}

getcontent('inc.php');
echo $var1;
?>

当我运行 test.php 时输出错误

Notice: Undefined variable: var1 in \www\test.php on line 7 

但是当我将 test.php 文件更改为此

<?php
include ('inc.php');
echo $var1;
?>

它的作品,并给我很好的输出

foobar

【问题讨论】:

    标签: php


    【解决方案1】:

    当你这样做时

    function getcontent($file) {
        include ($file);
    }
    getcontent('inc.php');
    

    它包括

    function getcontent($file) {
        $var1 = "foo";
        $var1 .= "bar";
    }
    

    实际上,您的变量包含在函数内部,而在函数外部不可见,因此会出现错误消息。

    See this SO answer.

    【讨论】:

    • 所以这将不起作用我包含在 inc.php 中???
    • 如果不是全局变量,则不在函数之外。
    【解决方案2】:

    当您将文件包含在 getcontent 函数中时,变量的行为就像在那里定义的一样,并且对外部不可见。

    如果您将它们声明为global,它会起作用。

    【讨论】:

      【解决方案3】:

      您必须将 $var1 声明为全局变量。

      global $var1;
      
      $var1 = "foo";
      $var1 .= "bar";
      

      $GLOBALS['var1'] = "foo";
      $GLOBALS['var1'] .= "bar";
      

      【讨论】:

      • 他没有 $var2 ;-)。我确定你只有 ment $var1。
      • @Stan,感谢观察,我已经完成了更新 =)
      猜你喜欢
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      相关资源
      最近更新 更多