Braces
Many languages use curly braces as scope boundaries, and only the curly braces of functions in PHP form a new scope.
<?phpif (True) {$a = ' var a ';} Var_dump ($a); for ($i = 0; $i < 1; $i + +) {$b = ' var b '; for ($i = 0; $i < 1; $i + +) {$c = ' var c ';} Var_dump ($c);} Var_dump ($b); Var_dump ($c);? >
The operating result is:
String (5) "Var a" string (5) "Var C" string (5) "Var B" string (5) "Var C"
Visible if and for curly braces do not constitute a new scope.
and the function:
<?phpfunction Test () {$test = ' var test ';} Test (); Var_dump ($test);? >
The result is:
Null
Global keyword
PHP is executed in a. php script, and during the execution of a. php script, you can include and require other PHP scripts in the execution process.
Executes a. php script that shares a global domain with the script that Include/require comes in.
The global keyword, regardless of the layer, refers to a variable of the world domain.
<?php$test = ' global test '; function A () {$test = ' Test in a () '; function B () {Global $test; Var_dump ($test);} b ();} A ();? >
The execution results are:
String (one) "Global test"
Closed Package
A closure scope is similar to a function where the inner layer accesses the outer variable and the outer layer cannot access the inner variable.
<?phpfunction A () {$test = ' Test in a () '; function B () {var_dump ($test);//$test cannot be accessed $varb = ' Varb in B () ';} b (); Var_dump ($varb); $varb also cannot be accessed by}a ();? >
Execution Result:
NULL NULL
Extended reading:
- Variable scope:http://www.php.net/manual/en/language.variables.scope.php
- PHP RFC closures:http://wiki.php.net/rfc/closures
PHP variable scope (curly braces, global, closures)