天堂网中文在线www,夜夜影院未满十八勿进,人妻精品久久无码区 http://www.aucma-it.com/blog 中山php|最優網絡 Mon, 13 May 2013 04:56:43 +0000 en hourly 1 http://wordpress.org/?v=3.1.4 php函數體里調用外部變量 http://www.aucma-it.com/blog/view-143.html http://www.aucma-it.com/blog/view-143.html#comments Thu, 18 Aug 2011 13:47:21 +0000 lin http://www.aucma-it.com/blog/?p=143

在程序開發中,有時在一個函數里面需要調用到函數體以外的變量,這個時候有幾種方法

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

global $string;

$string = 'test';

function __(){
return $string;
}

也可以在函數的內部聲明,如:

$string = 'test';

function __(){

global $string;
return $string;
}

當需要調用的變量只有少數的時候可以這樣用,那么如果是需要使用大量已經定義過的變量或者甚至是全部變量的時候如何處理呢?可以這樣處理,用到PHP的超全局數組$GLOBALS和extract()函數

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.

大概意思是:

這個一個由所有變量組成的數組。變量名就是該數組的索引。并且該數組是超全局數組,在使用時不必聲明global $variable;

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

所以綜上所述,只要在函數體里面寫上下面一句話就可以實現調用到外部的所有變量了

$string = 'test';

$num = 100;

function __(){

echo$string,$num;
}

extract($GLOBALS,EXTR_SKIP);

]]> http://www.aucma-it.com/blog/view-143.html/feed 26

主站蜘蛛池模板: 元江| 章丘市| 佛学| 婺源县| 宁明县| 天气| 黄骅市| 河津市| 芷江| 姜堰市| 闽清县| 肥东县| 南京市| 青河县| 延川县| 稻城县| 神农架林区| 石泉县| 元谋县| 玉林市| 鹤峰县| 天台县| 静乐县| 彝良县| 商城县| 常熟市| 波密县| 荣成市| 徐水县| 三穗县| 定南县| 历史| 柳江县| 南昌县| 大化| 凤台县| 峨眉山市| 固镇县| 田阳县| 抚顺县| 元谋县|