Home Backend Development PHP Tutorial PHP学习之全局变量

PHP学习之全局变量

Jun 23, 2016 pm 01:25 PM

PHP 的全局变量和 C 语言有一点点不同:在 C 语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能不小心就改变了一个全局变量。因此PHP 中全局变量在函数中使用时必须声明为 global。

来看一下下面的这个例子:

<?php$a = 1; /* global scope */function Test(){    echo $a; /* reference to local scope variable */}Test();?>
Copy after login

  

这个脚本不会有任何输出,因为 echo 语句引用了一个局部版本的变量 $a,而且在这个范围内,它并没有被赋值。

再看一个使用 global 的例子:

Example #1 使用 global

<?php$a = 1;$b = 2;function Sum(){    global $a, $b;    $b = $a + $b;}Sum();echo $b;?>
Copy after login

  

以上脚本的输出将是"3"。在函数中声明了全局变量 $a 和 $b 之后,对任一变量的所有引用都会指向其全局版本。对于一个函数能够声明的全局变量的最大个数,PHP 没有限制。

在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成:

Example #2 使用 $GLOBALS 替代 global

<?php$a = 1;$b = 2;function Sum(){    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];}Sum();echo $b;?>
Copy after login

  

$GLOBALS 是一个关联数组,每一个变量为一个元素,键名对应变量名,值对应变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处:

Example #3 演示超全局变量和作用域的例子

<?phpfunction test_global(){    // 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。    global $HTTP_POST_VARS;    echo $HTTP_POST_VARS['name'];    // Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。    echo $_POST['name'];}?>
Copy after login

  

全局变量的引用

请记住:如果在一个函数内部给一个声明为 global 的变量赋于一个引用,该引用只在函数内部可见。

在 Zend 引擎 1 代,它驱动了 PHP4,对于变量的 static 和 global 定义是以引用的方式实现的。例如,在一个函数域内部用 global 语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为,如以下例子所演示的:

<?phpfunction test_global_ref() {    global $obj;    $obj = &new stdclass;}function test_global_noref() {    global $obj;    $obj = new stdclass;}test_global_ref();var_dump($obj);test_global_noref();var_dump($obj);?>
Copy after login

  

以上例程会输出:


NULL
object(stdClass)(0) {
}

第一次输出NULL,原因是因为 global $var; 是 $var =& $GLOBALS['var']; 的简写。从而将其它引用赋给 $var 只改变了本地变量$var的引用。
也就是说$obj = &new stdclass;这个语句改变了局部变量$obj的指向, global $obj 这句语句造成的效果已经被覆盖了。

 
Copy after login
Copy after login

类似的行为也适用于 static 语句。引用并不是静态地存储的:

Copy after login
Copy after login
Copy after login

<?phpfunction &get_instance_ref() {    static $obj;    echo 'Static object: ';    var_dump($obj);    if (!isset($obj)) {        // 将一个引用赋值给静态变量        $obj = &new stdclass;    }    $obj->property++;    return $obj;}function &get_instance_noref() {    static $obj;    echo 'Static object: ';    var_dump($obj);    if (!isset($obj)) {        // 将一个对象赋值给静态变量        $obj = new stdclass;    }    $obj->property++;    return $obj;}$obj1 = get_instance_ref();$still_obj1 = get_instance_ref();echo "\n";$obj2 = get_instance_noref();$still_obj2 = get_instance_noref();?>
Copy after login

  

Copy after login
Copy after login
Copy after login

以上例程会输出:

Copy after login
Copy after login
Copy after login


Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

 
Copy after login
Copy after login

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles