首先我有下面这样两个程序,只有global的顺序不一样 ,但是输出我就搞不懂了。。
<?
$a=22;
function f()

    $a=11;
    global $a;
    echo "inside the function ".$a."<br>";  
}
f();
echo "outside the function ".$a."<br>";
$b=22;
function ff()

    global $b;
    $b=11;
    echo "inside the function ".$b."<br>";  
}
ff();
echo "outside the function ".$b."<br>";
?>
输出为:
inside the function 22
outside the function 22
inside the function 11
outside the function 11
f()函数中的global $a;为什么声明的是外面那个$a=22;这个变量,。而ff()函数中的global $b;又是在声明下面的$b=11;这个变量了呢??

解决方案 »

  1.   


    a=22; 
    function f() 

        $a=11; //定义变量$a指向11
        global $a; //更改变量$a,$a指向外部变量22
        echo "inside the function ".$a." <br>";  

    f(); 
    echo "outside the function ".$a." <br>"; 
    $b=22; 
    function ff() 

        global $b; //变量$b指向外部22
        $b=11; //更改变量$b指向11
        echo "inside the function ".$b." <br>";  

    ff(); 
    echo "outside the function ".$b." <br>"; 
      

  2.   

    function f() 

        $a=11;  //函數域的$a 
        global $a; //宣告使用外部變數 $a
        echo "inside the function ".$a." <br>"; //此時已經是用外部變數 $a 的值了,外部變數$a的值沒有換過,還是22 
    }function ff() 

        global $b; //宣告使用外部變數 $b
        $b=11;     //將外部變數 $b 的值換成 11
        echo "inside the function ".$b." <br>"; //此時還是使用外部變數 $b的值,剛才$b值已經換了,所以是11 

    都是作用域的問題
      

  3.   

    谢谢啦!我理解了global用法了!大概是在函数内部用外部声明的变量时,必须用global来声明一下!也就是global只对外部变量有作用!