The use of "PHP" Global variables with PHP

Source: Internet
Author: User
PHP's global variables and the rest of the programming language are different, in most programming languages, the global variable under its function, the class automatically take effect, unless overridden by a local variable, or do not allow the declaration of the same name and type of local variables, but the global variables in PHP is not in effect by default. In PHP, global variables must be declared global when used in functions, and global is only useful when defined in a function. In other words, global is defined as globally variable, but this global variable is not applied to the entire site, but applies to the current page, including all files of include or require.

To illustrate this problem directly with an example, the following code:


Very simply, declare a global variable $a=5, and then declare a function test () to print the global variable, then call the test (), according to the General programming language thinking, here the output must be 5, however, in the actual implementation is the following effect:

Direct error, said that a no definition, it is not unreasonable, but PHP is set, but I need to use a $ A as a global variable, there may be a lot of functions, many classes to use this $ A ah! This is, you need to use the global variable $ A each time to declare it with global keyword.

The following code is the correct demonstration:

The result is as follows, so that a can be used, each time you use the global variable $ A to declare it, this is the PHP rule.

It is important to note that the following code is wrong:

The same goes for the running result:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.