search

php variable scope

Nov 24, 2016 pm 01:47 PM
php

The scope of a variable is the context in which it is defined (that is, its effective scope). Most PHP variables have only a single scope. This single scope span also includes files introduced by include and require . For example:

<?php
    $a = 1;
    include &#39;b.inc&#39;;
?>

This variable $a will take effect in the include file b.inc. However, in user-defined functions, a local function scope will be introduced. Any variables used inside a function will be restricted to the local function scope by default. For example:

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

This script will not produce any output because the echo statement refers to a local version of the variable $a, and it is not assigned a value in this scope. You may notice that PHP's global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. This may cause some problems, someone may accidentally change a global variable. Global variables in PHP must be declared global when used in functions.

global keyword

First, an example of using global:

Example #1 Using global

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

The output of the above script will be "3". After global variables $a and $b are declared in a function, all references to either variable point to its global version. PHP has no limit on the maximum number of global variables that a function can declare.

The second way to access variables in the global scope is to use special PHP custom $GLOBALS array. The previous example can be written as:

Example #2 Use $GLOBALS instead of global

<?php
    $a = 1;
    $b = 2;
    function Sum()
    {
        $GLOBALS[&#39;b&#39;] = $GLOBALS[&#39;a&#39;] + $GLOBALS[&#39;b&#39;];
    }
    Sum();
    echo $b;
?>

$GLOBALS is an associative array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the content of the variable. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable. The following example shows the usefulness of superglobal variables:

Example #3 Example demonstrating superglobal variables and scope

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

Using static variables

Another important feature of variable scope is static variables. Static variables only exist in the local function scope, but their values ​​are not lost when program execution leaves this scope. Take a look at the following example:

Example #4 Demonstrates an example that requires a static variable

<?php
    function Test()
    {
        $a = 0;
        echo $a;
        $a++;
    }
?>

This function is not very useful because it will set the value of $a to 0 and output 0 every time it is called. $a++, which increments the variable by one, has no effect because the variable $a no longer exists once the function exits. To write a counting function that will not lose the current count value, define the variable $a as static:

Example #5 Example of using static variables

<?php
    function test()
    {
        static $a = 0;
        echo $a;
        $a++;
    }
?>

Now, the variable $a is only used when test( is called for the first time ) function is initialized, and every time the test() function is called thereafter, the value of $a will be output and incremented by one.

Static variables also provide a way to deal with recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely. You must ensure that there are adequate means to terminate recursion. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:

Example #6 Static variables and recursive functions

<?php
    function test()
    {
        static $count = 0;
        $count++;
        echo $count;
        if ($count < 10) {
            test();
        }
        $count--;
    }
?>

Static variables can be declared as in the example above. Assigning it with the result of an expression in a declaration will result in a parsing error.

Example #7 Declare static variables

<?php
    function foo(){
        static $int = 0; // correct
        static $int = 1+2; // wrong (as it is an expression)
        static $int = sqrt(121); // wrong (as it is an expression too)
        $int++;
        echo $int;
    }
?>

Static declarations are resolved at compile time.

There is nothing wrong with using the global keyword outside of a function. Can be used when including files within a function.

References to global and static variables

In Zend engine 1 generation, which drives PHP4, static and global definitions of variables are implemented in the form of references. For example, a true global variable imported with the global statement inside a function scope actually establishes a reference to the global variable. This may lead to unexpected behavior, as demonstrated in the following example:

<?php
    function 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);
?>

The above routine will output:

NULL
object(stdClass)(0) {}

Similar behavior also applies to static statements . References are not stored statically:

<?php
    function &get_instance_ref() {
        static $obj;
        echo &#39;Static object: &#39;;
        var_dump($obj);
        if (!isset($obj)) {
           // 将一个引用赋值给静态变量
           $obj = &new stdclass;
        }
        $obj->property++;
        return $obj;
    }
    function &get_instance_noref() {
        static $obj;
        echo &#39;Static object: &#39;;
        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();
?>

The above routine will output:

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

The above example demonstrates that when a reference is assigned to a static variable, its value is not remembered the second time the &get_instance_ref() function is called. live.


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
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools