Heim  >  Artikel  >  Backend-Entwicklung  >  PHP中全局变量global详解_PHP教程

PHP中全局变量global详解_PHP教程

WBOY
WBOYOriginal
2016-07-13 17:14:581005Durchsuche

本文章来详细的介绍关于PHP中全局变量global的方法,有需要了解global函数使用方法的朋友可参考本文章。

变量的范围即它定义的上下文背景(也就是它的生效范围)。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。例如:

 代码如下 复制代码

$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 语言有一点点不同,在 C 语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能不小心就改变了一个全局变量。PHP 中全局变量在函数中使用时必须申明为global。

今天就遇到了php 全局变量不起作用的问题.

先上一段简单的代码:

 代码如下 复制代码
$a = 0 ;
function Test()
{
    $a =1;
}
Test();
echo $a;
?>

上面的代码中输出是0,那是因为函数体Test内$a变量被缺省设置为局部变量,$a的作用域就是在Test内.修改代码如下

 代码如下 复制代码
$a = 0 ;
function Test()
{
    global $a;//申明函数体Test内使用的$a变量为global全局变量
    $a =1;
}
Test();
echo $a;
?>

申明函数体Test内使用的$a变量为global全局变量后,使得$a的作用全局,所以输出为1.
上面的实例只是基本的global全局变量知识,下面我们看看复杂点的:

//A.php 文件

 代码如下 复制代码

function Test_Global()
{  
    include 'B.php';  
    Test();  
}  

$a = 0 ;
Test_Global();
echo $a;
?> 

//B.php 文件

function Test()
{
    global $a;//申明函数体Sum内使用的$a变量为global全局变量
    $a =1;
}
?>

为什么输出的却是0?!!

在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内(包括include 和 require 导入的文件内的变量)!
解释:A.php文件的内Test_Global是定义好的第三方函数,该函数用include导入了B.php文件内的$a的global全局变量,所以$a被限制在Test_Global局部函数范围内,所以B.php文件内的$a的作用范围都在Test_Global内,而不是作用了整个A.php内….

解决方案:

1. 冲出局部函数

 代码如下 复制代码

//A.php 文件

function Test_Global()
{  
    Test();  
}  
include 'B.php';   //将include 从局部Test_Global函数中移出
$a = 0 ;
Test_Global();
echo $a;
?> 

//B.php 文件

function Test()
{
    global $a;
    $a =1;
}
?>

2.优秀的访问器

 代码如下 复制代码

//A.php 文件
include 'B.php'; 
$a =0;
Set_Global($a);
echo $a;
?> 

//B.php 文件

function Set_Global(&$var)
{
    $var=1;
}
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/628915.htmlTechArticle本文章来详细的介绍关于PHP中全局变量global的方法,有需要了解global函数使用方法的朋友可参考本文章。 变量的范围即它定义的上下文背景...
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