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条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来