最優(yōu)良人 » 變量 http://www.dgkai.cn/blog 中山php|最優(yōu)網(wǎng)絡(luò) Mon, 13 May 2013 04:56:43 +0000 en hourly 1 http://wordpress.org/?v=3.1.4 php函數(shù)體里調(diào)用外部變量 http://www.dgkai.cn/blog/view-143.html http://www.dgkai.cn/blog/view-143.html#comments Thu, 18 Aug 2011 13:47:21 +0000 lin http://www.dgkai.cn/blog/?p=143

在程序開(kāi)發(fā)中,有時(shí)在一個(gè)函數(shù)里面需要調(diào)用到函數(shù)體以外的變量,這個(gè)時(shí)候有幾種方法

可以再聲明變量的時(shí)候聲明為全局變量,如:

global $string;

$string = 'test';

function __(){
return $string;
}

也可以在函數(shù)的內(nèi)部聲明,如:

$string = 'test';

function __(){

global $string;
return $string;
}

當(dāng)需要調(diào)用的變量只有少數(shù)的時(shí)候可以這樣用,那么如果是需要使用大量已經(jīng)定義過(guò)的變量或者甚至是全部變量的時(shí)候如何處理呢?可以這樣處理,用到PHP的超全局?jǐn)?shù)組$GLOBALS和extract()函數(shù)

PHP手冊(cè)對(duì)$GLOBAL的說(shuō)明是這樣的:

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.

大概意思是:

這個(gè)一個(gè)由所有變量組成的數(shù)組。變量名就是該數(shù)組的索引。并且該數(shù)組是超全局?jǐn)?shù)組,在使用時(shí)不必聲明global $variable;

extract()函數(shù)的作用是把數(shù)組的鍵名作為變量名,數(shù)組的鍵值作為變量的值。

所以綜上所述,只要在函數(shù)體里面寫(xiě)上下面一句話(huà)就可以實(shí)現(xiàn)調(diào)用到外部的所有變量了

$string = 'test';

$num = 100;

function __(){

echo$string,$num;
}

extract($GLOBALS,EXTR_SKIP);

]]> http://www.dgkai.cn/blog/view-143.html/feed 26