The use of "PHP" Global variables with PHP

Source: Internet
Author: User

PHP's global variables are different from the rest of the programming languages, and in most programming languages the global variables themselves take the initiative in their functions and classes. Unless overridden by a local variable, or does not agree to declare a local variable of the same name and type at all. However, the global variables in PHP are not in effect by default. A global variable in PHP must be declared global when used in a function. Global this keyword is only practical when defined in a function. In other words, global is defined as the role of Globals. However, this global variable is not applied to the entire site. Instead, it applies to the current page, which contains all the files for include or require.

Use a sample directly to illustrate the problem, such as the following code:

<?php$a=5;function Test () {echo $a;} Test ();?

>


Very easy, declare a global variable $a=5, and then declare a function test () to print this global variable, later. Call this test (), in accordance with the general programming language of thinking. The output here must be 5, however, the actual operation is for example the following effect:


Direct error, said that a undefined, it is not unreasonable, but PHP is set, but I need to use a $ A as a global variable, it is possible that there are a lot of functions, very many classes to use this $ A ah!

This is, you need to use global variable $ A each time to declare it with global keyword.

For example the following code is the correct demonstration:

<?php$a=5;function Test () {global $a; echo $a;} Test ();?

>

The results of the execution are 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, for example, the following code is wrong:

<?

Phpglobal $a; $a =5;function test () {echo $a;} Test ();?

>

The result of the execution is the same:


The use of "PHP" Global variables with PHP

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: info-contact@alibabacloud.com 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.