Home > php教程 > php手册 > body text

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

WBOY
Release: 2016-06-13 08:53:04
Original
1158 people have browsed it

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

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

<?<span>php
</span><span>$x</span>=5<span>;
</span><span>$y</span>=10<span>;

</span><span>function</span><span> myTest()
{
</span><span>global</span> <span>$x</span>,<span>$y</span><span>;
</span><span>$y</span>=<span>$x</span>+<span>$y</span><span>;
}

myTest();
</span><span>echo</span> <span>$y</span>; <span>//</span><span> 输出 15</span>
?>
Copy after login

如果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
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!