PHP中global和$GLOBALS的用法和区别


相同点:

 1、在函数内部使用函数体外声明的变量

$a = 1;
function test1()
{
    echo $a;
}

function test2()
{
    global $a;
    echo $a;
}

function test3()
{
    echo $GLOBALS['a'];
}


test1(); //Notice: Undefined variable: a
test2(); //1
test3(); //1

2、在函数体外声明没有意义,函数内无法使用

global $a;
$a = 1;
function test1()
{
    echo $a;
}
$GLOBALS['b'] = 2;
function test2()
{
    echo $b;
}
test1(); //Notice: Undefined variable: a
test2(); //Notice: Undefined variable: b

区别:

global是引用$GLOBALS直接就是变量本身

$a = 1;
$b = 2;
function test2()
{
    global $a;
    echo $a;
    unset($a);
}

function test3()
{
    echo $GLOBALS['b'];
    unset($GLOBALS['b']);

}
test2(); //1
echo $a; //1
test3(); //1
echo $b; //Notice: Undefined variable: b

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM