gpt4 book ai didi

php - 函数外的变量是全局变量吗?

转载 作者:可可西里 更新时间:2023-11-01 13:04:19 26 4
gpt4 key购买 nike

<?php

$foo = 1;

function meh(){
// <-- $foo can't be accessed
}

它看起来不像一个全局变量。但是,如果它在函数之外,它是否会像全局的东西那样有缺点?

最佳答案

在任何函数之外定义的所有变量都在全局范围内声明。如果你想访问一个全局变量,你有两个选择:

  1. 使用global关键字

    <?php
    $a = 1;
    $b = 2;

    function Sum()
    {
    global $a, $b;

    $b = $a + $b;
    }
    ?>
  2. 或者使用$GLOBALS

    <?php
    $a = 1;
    $b = 2;

    function Sum()
    {
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
    }
    ?>

    阅读更多信息 http://php.net/manual/en/language.variables.scope.php

关于php - 函数外的变量是全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com