花括號
很多語言都以花括號作為作用域界限,PHP中只有函數的花括號才構成新的作用域。
<?php if (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); ?>
運行結果是:
string(5) "var a" string(5) "var c" string(5) "var b" string(5) "var c"
可見if和for的花括號並無構成新的作用域。
而函數:
<?php function test() { $test = 'var test'; } test(); var_dump($test); ?>
結果是:
NULL
global關鍵字
PHP的執行是以一個.php腳本為單位,在一個.php腳本的執行過程中,可以include和require其他PHP腳本進來執行。
執行的.php腳本與include/require進來的腳本共享一個全局域(global scope)。
global關鍵字無論在哪層,所引用的都是全局域的變量。
<?php $test = 'global test'; function a() { $test = 'test in a()'; function b() { global $test; var_dump($test); } b(); } a(); ?>
執行結果是:
string(11) "global test"
閉包
閉包作用域跟函數類似,內層訪問外層變量,外層不能訪問內層變量。
<?php function a() { $test = 'test in a()'; function b() { var_dump($test); // $test不能被訪問 $varb = 'varb in b()'; } b(); var_dump($varb); // $varb也不能被訪問 } a(); ?>
執行結果:
NULL NULL
延伸閱讀:
- variable scope: http://www.php.net/manual/en/language.variables.scope.php
- php rfc closures:http://wiki.php.net/rfc/closures