PHP 全局变量(Global Scope Variable) vs 局部变量(Local Scope Variable)

本文探讨了PHP中全局变量(Global Scope Variable)与局部变量(Local Scope Variable)的区别。通过示例展示了如何在函数内部访问全局变量,包括使用`global`关键字声明以及通过参数传递。总结了两种在函数内使全局变量可见的方法:直接声明`global`或通过参数传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
<head>
<title>Writing Functions In PHP - Global Variable</title>
</head>
<body>
    <?php

        $bar = "outside"; // global scope variable

        function foo() {
            $bar = "inside"; // local scope variable
        }

        foo();
        echo $bar . "<br>";

    ?>
</body>
</html>

以上代码输出: outside.

<?php

    $bar = "outside";

    function foo() {
        global $bar; // declaring global variable
        $bar = "inside"; // local scope variable
    }

    foo();
    echo $bar . "<br>";

?>
以上代码输出:inside.

<html>
<head>
<title>Writing Functions In PHP - Global Variable</title>
</head>
<body>
    <?php

        $bar = "outside"; // global scope variable

        function foo2($var) {
            $var = "inside"; // local scope variable
            return $var;
        }

        $bar = foo2($bar);
        echo $bar . "<br>";

    ?>
</body>
</html>
以上代码输出:inside


总结:PHP中函数外全局变量在函数内可见的方法:

1.在函数内声明global 变量

2.通过传参的形式把全局变量传入函数

                                                                      



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值