duankousong9637 2016-01-10 14:09
浏览 117
已采纳

为什么我定义的变量未定义[重复]

I declared a new variable $var at the top of my document. Afterwards, I called a function which should output this variable.
Unfortunately, I get the following message:

Notice: Undefined variable: var

This is my code:

$var = "abc";

func ();
function func() {
    echo $var;
}
</div>
  • 写回答

3条回答 默认 最新

  • dongyou9373 2016-01-10 14:13
    关注

    In PHP, functions cannot access variables that are within the global scope unless the keyword global is used to 'import' the variable into the function's scope.

    You would fix it by doing this:

    function func() {
        global $var;
        echo $var;
    }
    

    Read more about scoping here: http://php.net/manual/en/language.variables.scope.php

    Any variable used inside a function is by default limited to the local function scope.

    In PHP global variables must be declared global inside a function if they are going to be used in that function.

    Global variables can also be accessed using $GLOBALS although I would avoid using that unless absolutely necessary.

    A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.

    Worth mentioning:

    It's worth linking to this discussion on globals and why you may not want to use them: Globals are evil . I'd say there is a preference to use classes instead, or simply pass in the variable as an argument to the function. I won't say not to use globals but at the very least be mindful of its use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计