views:

176

answers:

3

I have a function with a big hierarchy:

function func(){
    $a= 0; // Here the variable is 0
    while(...){
        echo $a; // gives me always 0
        for(...){
            if(...){
                if(...){
                    $num = func3();
                    $a = $num; // this $a does not corrospond to $a in the beginning
                }
            }
        }
    }
}

Does anyone know how I can change the value of $a from the nested scopes?

A: 

you probably are using $a in a previous scope or func3() has set "global $a;" or maybe the if statements are never reached

w35l3y
no that is only for func()
Granit
@Tim, someone with low self esteem downvoted everyone
w35l3y
A: 

Global it.

global $a;

func() {
  $a = 0;
  while() {
    echo $a;
    for() {
      if() {
        if() {
          $a = func3();
        }
      }
    }
  }
}
Tim
Why the downvote? Not complaining, just trying to understand better.
Tim
1. Because using a global scope is almost never the right answer. 2. The problem isn't a scope problem, since PHP doesn't create a new scope when it encounters a {} block.
Alan Storm
Alright, thanks! I learned something today :)
Tim
+3  A: 

Prior to PHP 5.3, PHP only has two scopes: global and local function scope. PHP 5.3 introduced closures, which complicated the scope situation a bit, but it doesn't look like you're using them here.

Unlike many other C style programming languages, brackets/blocks do not invoke another level of scopre. The $a you declare at the start of the function is the same $a that you're accessing later. If the value you're getting in $a is unexpected, it's the missing code (...) that's changing its value, either through an assignment or because it's being passed by reference into some other function that's changing its value.

Alan Storm