在程序開發(fā)中,有時在一個函數(shù)里面需要調(diào)用到函數(shù)體以外的變量,這個時候有幾種方法
可以再聲明變量的時候聲明為全局變量,如:
global $string;
$string = 'test';
function __(){
return $string;
}
也可以在函數(shù)的內(nèi)部聲明,如:
$string = 'test';
function __(){
global $string;
return $string;
}
當需要調(diào)用的變量只有少數(shù)的時候可以這樣用,那么如果是需要使用大量已經(jīng)定義過的變量或者甚至是全部變量的時候如何處理呢?可以這樣處理,用到PHP的超全局數(shù)組$GLOBALS和extract()函數(shù)
PHP手冊對$GLOBAL的說明是這樣的:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
大概意思是:
這個一個由所有變量組成的數(shù)組。變量名就是該數(shù)組的索引。并且該數(shù)組是超全局數(shù)組,在使用時不必聲明global $variable;
extract()函數(shù)的作用是把數(shù)組的鍵名作為變量名,數(shù)組的鍵值作為變量的值。
所以綜上所述,只要在函數(shù)體里面寫上下面一句話就可以實現(xiàn)調(diào)用到外部的所有變量了
$string = 'test';
$num = 100;
function __(){
echo$string,$num;
}
extract($GLOBALS,EXTR_SKIP);