Heim  >  Artikel  >  php教程  >  php 全局变量范围分析

php 全局变量范围分析

WBOY
WBOYOriginal
2016-06-13 12:22:28690Durchsuche

复制代码 代码如下:


$a = 1 ;
include 'b.inc' ;
?>


这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。

复制代码 代码如下:


$a = 1 ; /* global scope */
function Test ()
{
echo $a ; /* reference to local scope variable */
}
Test ();
?>


这个脚本不会有任何输出,因为 echo 语句引用了一个局部版本的变量 $a ,而且在这个范围内,它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同
PHP 中全局变量在函数中使用时必须申明为全局(global关键字)

复制代码 代码如下:


$a = 1 ;
$b = 2 ;
function Sum ()
{
global $a , $b ;
$b = $a + $b ;
}
Sum ();
echo $b ;
?>


以上脚本的输出将是“3”。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn