PHPs variable scoping -


this might seem trivial question, since realised after using php 8months, think requires attention. used strongly-typed languages such java, weakly-typed languages well(somehow).

ok, question in mind, defining variable within function, within 3rd level foreach loop.

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

in above example, last if condition return true, though $new var not declared global variable, how accessible outside foreach loop? shouldn't give undefined error ?

nb.i have looked @ php doc

much javascript, php's variables scoped function level. variable return true isset() in foreach,for or while loop after has been set. php doesn't have concept of loop scoping.

it's worth mentioning function scoping little stricter javascript's. without using use () statement closures function don't have access calling function's context:

function scopeone() {     $myvar = "hello";     $scopetwo = function () {         return isset($myvar);     };      $doesscopetwohaveaccesstoscopeone = $scopetwo();      if ($doesscopetwohaveaccesstoscopeone) {         echo "this won't true";     } else {         echo "scope 2 can not access variables in scope one";     } }  scopeone(); 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -