Home  >  Article  >  php教程  >  PHP global 关键字,phpglobal关键字

PHP global 关键字,phpglobal关键字

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

PHP global 关键字,phpglobal关键字

global关键字用于在函数内部访问全局变量。

<?php
$x = 5;
$y = 10;

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

myTest();
echo $x; //15

 php将所有全局变量存储在一个名为$GLOBALS[index]的数组里,index保存变量的名称,这个数组可以在函数内部访问,也可以直接更新全局变量;

上面的实例可以改写成下面这个样:

<?php
$x = 5;
$y=10;

function myTest(){
    $GLOBALS['x'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $x; //15
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