Home  >  Article  >  Backend Development  >  函数中全局变量的问题

函数中全局变量的问题

WBOY
WBOYOriginal
2016-06-23 14:00:23934browse

不用函数的时候,代码如下:

$lists = array();for( $i = 0; $i < 5 ; $i++ ){	$lists[] = $i;}echo json_encode($lists);


执行结果为:
[0,1,2,3,4]

我想把这个功能放到函数里,代码如下:
$lists = array();function testarray(){	for( $i = 0; $i < 5 ; $i++ )	{		$lists[] = $i;	}}testarray();echo json_encode($lists);


可是结果变成了这样:
[]

到底是怎么回事?请指教,谢谢。


回复讨论(解决方案)

在函数中直接使用变量并不会使其自动具有全局的作用范围,相反,你需要显式的声明Global。
如下:
$lists = array();
function testarray()
{
         global $lists;
for( $i = 0; $i  {
$lists[] = $i;
}
}
testarray();
echo json_encode($lists);


也可以通过传递参数的方法,可以避免使用全局变量造成迷惑。

用global是可以调用全局的变量,但不建议这样。
以传递参数方式实现会较好。

<?php$lists = array();function testarray(&$lists){    for( $i = 0; $i < 5 ; $i++ )    {        $lists[] = $i;    }}testarray($lists);echo json_encode($lists);?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn