---
title: "php 中的 global 与 $GLOBALS[]"
author: "marlay"
date: "2012-05-16T10:13:18Z"
tags: []
categories: ["Web前端"]
slug: "php-global-globals"
draft: false
lastmod: "2012-05-16T10:13:18Z"
id: 1532348
url: "https://marlay.iteye.com/blog/1532348"
---

global在函数产生 一个指向函数外部变量的别名 变量，而不是真正的函数外部变量，一但转变了别名 变量的指向地址，就会产生一些意料不到情况 ，例如例子1.

$GLOBALS\[]确确凿实调用是外部的变量，函数内外会始终维持一致！

可以对照 下面两个列子：

global：

&lt;?php

function myfunction(){  
    global $bar;  
    unset($bar);  
}  
$bar="someting";  
myfunction();  
echo $bar;  
?&gt;

输出：someting

$global\[]:

&lt;?php  
    function foo()  
{  
    unset($GLOBALS\['bar']);  
}

$bar = "something";  
foo();  
echo $bar;  
?&gt;

输出：空