search
HomeBackend DevelopmentPHP TutorialHow to get PHP super global variables (organized and shared)

In the previous article, I brought you "Understand PHP anonymous functions in five minutes (detailed examples)". This article introduces the relevant knowledge of anonymous functions in PHP in detail. This article will take a look at the issues related to super global variables that can be referenced inside functions. I hope it will be helpful to everyone!

How to get PHP super global variables (organized and shared)

PHP super global variables

Global variables defined outside the function cannot be referenced inside the function, but Sometimes you need to use these global variables within a function. In this case, you need to use super global variables. Super global variables can be referenced inside the function.

Several super global variables are predefined in PHP, which means that they can be referenced in the entire scope of a script. Without special instructions, super global variables can be used in functions and classes.

PHP super global variable

  • $GLOBALS

  • $_SERVER

  • $_REQUEST

  • $_POST

  • $_GET

  • $ _FILES

  • $_ENV

  • $_COOKIE

  • ## $_SESSION

Today we will first take a look at a few super global variables that are commonly used in daily use. Next, we will look at some usages and characteristics of these super global variables through some examples.

First of all, let’s take a look:

PHP $GLOBALS

$GLOBALS is a A predefined superglobal array that contains all variables available in the global scope. The name of the variable is the key of the array. $GLOBALS is accessible from the entire scope of a PHP script.

The example is as follows:


<?php 
//定义两个全局变量,函数内部不可以访问
$a = 75; 
$b = 25;
//定义函数
function addition() 
{ 
//将全局变量变为超级全局变量,这样在函数内部就可以正常访问了
$GLOBALS[&#39;c&#39;] = $GLOBALS[&#39;a&#39;] + $GLOBALS[&#39;b&#39;]; 
}
//调用函数
addition();
//输出函数内部定义的全局变量 
echo $c; 
?>

Output result:


How to get PHP super global variables (organized and shared)

$GLOBALS is not limited to must be used inside the function. Can be used anywhere in the program. As can be seen from the above example, global variables become super global variables, so that they can be accessed normally within the function.


global

There is also a keyword called

global that is very similar to $GLOBALS, which also allows us to Use global variables defined outside the function inside the function.

The syntax format is as follows:

global 变量1, 变量2, ...

global keyword can be followed by multiple variables as parameters, and multiple variables are separated by "," (comma). At the same time, you should pay attention to some key points when using global:

  • The global keyword cannot be used outside the function, but can only be used inside the function;

  • ## The #global keyword can only be used to refer to global variables outside the function, and cannot be directly assigned when referencing. The assignment and declaration statements need to be written separately;
  • Destroy a global variable inside the function using the global key When modifying variables with words, variables outside the function are not affected.
  • The example is as follows:

<?php
    $a = 1;
    $b = 2;
    $c = 3;
    function demo(){
        global $a, $b;
        echo "变量 a:".$a;
        echo "<br>变量 b:".$b;
        echo "<br>变量 c:".$c;
    }
    demo();
?>

In the above example, three variables are defined, but the global keyword only modifies two variables in the function, What impact will the output have?


Output result:

How to get PHP super global variables (organized and shared)It can be seen that the result only outputs variables a and b, because the global keyword is only modified within the function There are two, so the variable c is not used successfully.

Through two examples, we can see that compared with global, $GLOBALS has the following differences:

    global $ refers to the variable with the same name outside the function References are two variables that do not affect each other, while $GLOBALS[] refers to the external variable of the function itself, which is a variable.
  • $GLOBALS is not limited to being used inside a function and can be used anywhere in the program.

PHP $_SERVER##PHP $_SERVER is an array to be precise, $_SERVER contains Header information, path, script location and other information. The items in this array are created by the web server. Servers may ignore some, and not all items may be available on every server.

Next, I will give you an example of how to use PHP $_SERVER:

<?php 
//输出当前脚步的文件名
echo "<h3 id="输出当前脚步的文件名">输出当前脚步的文件名</h3>";
echo $_SERVER[&#39;PHP_SELF&#39;];
echo "<hr/>";
//当前脚步所在服务器的主机名
echo "<h3 id="当前脚步所在服务器的主机名">当前脚步所在服务器的主机名</h3>";
echo $_SERVER[&#39;SERVER_NAME&#39;];
echo "<hr/>";
//当前请求头中 Host
echo "<h3 id="当前请求头中-nbsp-Host">当前请求头中 Host</h3>";
echo $_SERVER[&#39;HTTP_HOST&#39;];
echo "<hr/>";
//引导用户代理到当前页的前一页的地址(如果存在)
echo "<h3 id="引导用户代理到当前页的前一页的地址-如果存在">引导用户代理到当前页的前一页的地址(如果存在)</h3>";
echo $_SERVER[&#39;HTTP_REFERER&#39;];
echo "<hr/>";
//用来检查浏览页面的访问者在用什么操作系统
echo "<h3 id="用来检查浏览页面的访问者在用什么操作系统">用来检查浏览页面的访问者在用什么操作系统</h3>";
echo $_SERVER[&#39;HTTP_USER_AGENT&#39;];
echo "<hr/>";
//包含当前脚本的路径
echo "<h3 id="包含当前脚本的路径">包含当前脚本的路径</h3>";
echo $_SERVER[&#39;SCRIPT_NAME&#39;];
?>

Output results


Share with everyone , More important elements in the $_SERVER variable: How to get PHP super global variables (organized and shared)

    $_SERVER['PHP_SELF']
  • ---The file name of the currently executing script, related to document root .

  • $_SERVER['GATEWAY_INTERFACE']
  • ---The version of the CGI specification used by the server.

  • $_SERVER['SERVER_ADDR']---The IP address of the server where the script is currently running.

  • $_SERVER['SERVER_NAME']---The host name of the server where the script is currently running.

  • $_SERVER['SERVER_SOFTWARE']---Server identification string, given in the header information when responding to the request.

  • $_SERVER['SERVER_PROTOCOL']---The name and version of the communication protocol when requesting the page.

  • $_SERVER['REQUEST_METHOD']---The request method used to access the page.

  • $_SERVER['REQUEST_TIME']---The timestamp when the request started. Available since PHP 5.1.0.

  • $_SERVER['QUERY_STRING']---query string (query string), if any, use it to access the page.

  • $_SERVER['HTTP_ACCEPT']---The content of the Accept: item in the current request header, if it exists.

  • $_SERVER['HTTP_ACCEPT_CHARSET']---The content of the Accept-Charset: item in the current request header, if it exists.

  • $_SERVER['HTTP_HOST']---The content of the Host: item in the current request header, if it exists.

  • $_SERVER['HTTP_REFERER']---Direct the user agent to the address of the previous page of the current page (if it exists).

  • $_SERVER['HTTPS']---If the script is accessed through the HTTPS protocol, it is set to a non-empty value.

  • $_SERVER['REMOTE_ADDR']---The IP address of the user browsing the current page.

  • $_SERVER['REMOTE_HOST']---The host name of the user browsing the current page. DNS reverse resolution does not depend on the user's REMOTE_ADDR.

  • $_SERVER['REMOTE_PORT']---The port number used on the user's machine to connect to the Web server.

  • $_SERVER['SCRIPT_FILENAME']---The absolute path of the currently executing script.

  • $_SERVER['SERVER_ADMIN']---This value specifies the SERVER_ADMIN parameter in the Apache server configuration file. If the script is running on a virtual host, this value is that of that virtual host.

  • $_SERVER['SERVER_PORT']---The port used by the Web server. The default value is "80". If using SSL secure connection, this value is the HTTP port set by the user.

  • $_SERVER['SERVER_SIGNATURE']---A string containing the server version and virtual host name.

  • $_SERVER['PATH_TRANSLATED']---The base path of the file system (not the document root directory) where the current script is located. This is the result after the server has been imaged from a virtual to real path.

  • $_SERVER['SCRIPT_NAME']---Contains the path of the current script. This is useful when the page needs to point to itself. The __FILE__ constant contains the full path and file name of the current script (such as an include file).

  • $_SERVER['SCRIPT_URI']---URI is used to specify the page to be accessed. For example "/index.html".

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to get PHP super global variables (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

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
What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment