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 Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment