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