Home >Backend Development >PHP Tutorial > PHP 全局变量在用户自定义函数内部不足见

PHP 全局变量在用户自定义函数内部不足见

WBOY
WBOYOriginal
2016-06-13 13:08:251030browse

PHP 全局变量在用户自定义函数内部不可见

全局变量是定义在任何函数之外,其作用域是整个PHP文件,但在函数内部不可见,若要使其可见就需要用global 声明。

?

<?php
$val1 = 1;
$val2 = 2;
function test()
{
   echo "start\n";
   echo "val1: ".$val1."\n";                                // 不可见
      echo "val2: ".$val2."\n";                             // 不可见

   global $val2;                                    //global声明了$val2, 使其可见
   echo "声明:global val2 以后\n"; 
      echo "val2: ".$val2."\n";                                //$val2 可见了
   $val2 = 100; 
   echo "end\n";
   $val1 = 100;                                                    //只是局部变量
}
test();
echo "调用了test()以后:\nval2 = ".$val2."\n";      //$val2被test()函数改变了
echo "val1 = ".$val1."\n";                                    //没有被test()改变
?>

?
结果:

start
val1:
val2:
声明:global val2 以后
val2: 2
end


调用了test()以后:
val2 = 100
val1 = 1

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