Abt the global Variable Scope

Discussion in 'PHP' started by fengfeng, Oct 1, 2007.

  1. #1
    Hello,everyone.im new here and im green hand now.Thanks for ur replies!!

    i have write a php program.
    <?php
    $a=1;
    function qq(){
    $a=4;
    global $a ;
    }
    qq();
    echo $a;
    ?>
    PHP:
    i donno why the program would echo out 1 .
    i think the program would echo out 4,because the global $a is after the $a=4
    Thanks for ur replies!!
     
    fengfeng, Oct 1, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Move the global above the $a=4.

    First make it global, then assign a new value to it.
     
    nico_swd, Oct 1, 2007 IP
  3. fengfeng

    fengfeng Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    thank u.i just want to know why i make $a into global in the qq function,but the $a outside the funciton be globaled.
     
    fengfeng, Oct 1, 2007 IP
  4. fengfeng

    fengfeng Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    in face ,there r 2 $a in the program,one is outside the function and one is in it,when i make the $a global,which $a would be globaled??
     
    fengfeng, Oct 1, 2007 IP
  5. TwistMyArm

    TwistMyArm Peon

    Messages:
    931
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Don't think of it as "making it global", think of it as "from now on, when I refer to $a, I want to be using the $a in the global namespace".
     
    TwistMyArm, Oct 1, 2007 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    The $a outside the function is in your global scope. To access variables inside a function (without passing them as argument), you need to use global before this variable is being used.

    Not sure if that made sense to you, however, you might want to have a look at the official manual page which explains it better.

    www.php.net/global
     
    nico_swd, Oct 1, 2007 IP
  7. fengfeng

    fengfeng Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    "from now on" is very great opinion.Thank u:):)
     
    fengfeng, Oct 1, 2007 IP