Home  >  Article  >  php教程  >  php 学习日志- 变量作用域,变量

php 学习日志- 变量作用域,变量

WBOY
WBOYOriginal
2016-06-13 08:53:041079browse

php 学习日志- 变量作用域,变量

1、global 函数内访问全局变量

php
$x=5;
$y=10;

function myTest()
{
global $x,$y;
$y=$x+$y;
}

myTest();
echo $y; // 输出 15
?>

如果myTest函数里不使用global,无法使用

PHP 将所有全局变量存储在一个名为 $GLOBALS[index] 的数组中。 index 保存变量的名称。这个数组可以在函数内部访问,也可以直接用来更新全局变量。 如$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y']

2、Static 当一个函数完成时,它的所有变量通常都会被删除。然而,有时候您希望某个局部变量不要被删除。

function myTest()
{
static $x=0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();

0
1
2

  每次调用该函数时,该变量将会保留着函数前一次被调用时的值。该变量仍然是函数的局部变量。

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