中山php|最优网络中山做网站 中山php建站

最优良人

2011/08/18 at 21:47

php函数体里调用外部变量

在程序开发中,有时在一个函数里面需要调用到函数体以外的变量,这个时候有几种方法

可以再声明变量的时候声明为全局变量,如:

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);

标签:,
-