LogixMaster
LogixMaster

Reputation: 586

PHPs variable scoping

This might seem as a trivial question, but since I just realised this after using php for about 8months, I think it requires some attention. I am used to strongly-typed languages such as java, but I do like weakly-typed languages as well(somehow).

Ok, so to the question in mind, I am defining a variable within a function, within a 3rd level foreach loop. Something like

for($x =0; $x <= 20; $x++){
   for($x =0; $x <= 5; $x++){
      foreach($arr as $var){
        $new_arr = $var;
      }
       
      if(isset($new_arr)){
         //code executes here     
      }

   }
}

In the above example, the last if condition does return true, even though the $new var is not declared as a global variable, so how would it be accessible outside the foreach loop? Shouldn't it give an undefined error ?

nb.I have already looked at the php doc

Upvotes: 0

Views: 95

Answers (2)

Steve B
Steve B

Reputation: 644

Much like javascript, PHP's variables are scoped to a function level. So your variable will return true for isset() in any foreach,for or while loop after it has been set. PHP doesn't have any concept of loop scoping.

It's also worth mentioning that the function scoping is a little stricter than javascript's. Without using the use () statement closures with a function don't have access to the calling function's context:

function ScopeOne() {
    $myVar = "hello";
    $scopeTwo = function () {
        return isset($myVar);
    };

    $doesScopeTwoHaveAccessToScopeOne = $scopeTwo();

    if ($doesScopeTwoHaveAccessToScopeOne) {
        echo "this won't be true";
    } else {
        echo "Scope Two can not access variables in scope one";
    }
}

ScopeOne();

Upvotes: 5

even though the $new var is not declared as a global variable, so how would it be accessible outside the foreach loop?

You are assuming foreach as a function, A foreach is not a function, but a language construct.

A variable that has been assigned a value inside control structures will not be affected by scope issues , Even the innermost control structure can access it. !

The isset checks whether the variable has been assigned a value or not. So when you reach your innermost foreach the value will be assigned , so when you do the isset obviously it will return true.

Upvotes: 5

Related Questions