略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 超全局变量

2024-11-22

超全局变量

超全局变量在全部作用域中始终可用的内置变量

说明

PHP 中的许多预定义变量都是“超全局的”,这意味着它们在一个脚本的全部作用域中都可用。在函数或方法中无需执行 global $variable; 就可以访问它们。

这些超全局变量是:

注释

注意: 变量可用性

默认情况下,所有的超全局变量都是可用的。但是,有一些指令会影响这种可用性。更多信息,参见文档 variables_order.

注意: 可变变量

在函数或类方法中,超全局变量不能被用作可变变量

add a noteadd a note

User Contributed Notes 3 notes

up
38
kitchin
9 years ago
Since PHP 5.4, you cannot use a superglobal as the parameter to a function. This causes a fatal error:

function foo($_GET) {
  // whatever
}

It's called "shadowing" a superglobal, and I don't know why people ever did it, but I've seen it out there. The easy fix is just to rename the variable $get in the function, assuming that name is unique.

There was no deprecation warning issued in previous versions of PHP, according to my testing, neither in 5.3 nor 5.2. The error messages in 5.4 are:
Fatal error: Cannot re-assign auto-global variable _GET in...
Fatal error: Cannot re-assign auto-global variable _COOKIE in...
etc.
up
-16
mife
2 years ago
// You do need global in this special situation

function get_var($varname){
  global $$varname;
  echo $$varname;
}

show_var('_POST');
up
-51
php (a) timstamp.co.uk
4 years ago
For those wondering if register_globals also makes global variables available inside functions - it doesn't.

Running this code on a PHP52 webserver with register_globals enabled, using url:
http://localhost?hello=campers

<?php
function abc() {
    echo
"in func: '$hello' \n"; // outputs "in func: '' "
}
echo
"global: '$hello' \n"; // outputs "global: 'campers' "
abc();

官方地址:https://www.php.net/manual/en/language.variables.superglobals.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3