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

<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.通過傳參的形式把全局變量傳入函數

                                                                      



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章