Home >Backend Development >PHP Tutorial >Analysis on the scope of application of php global variables

Analysis on the scope of application of php global variables

WBOY
WBOYOriginal
2016-07-25 09:03:25896browse
  1. $a = 1 ;
  2. include 'b.inc' ;
  3. ?>
Copy code

Here 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.

  1. $a = 1 ; /* global scope */
  2. function Test ()
  3. {
  4. echo $a ; /* reference to local scope variable */
  5. }
  6. Test ();
  7. ?>
Copy code

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 those in C Global variables in PHP must be declared global (global keyword) when used in functions.

  1. $a = 1 ;
  2. $b = 2 ;
  3. function Sum ()
  4. {
  5. global $a , $b ;
  6. $b = $a + $b ;
  7. }
  8. Sum ();
  9. echo $b ;
  10. ?>
Copy code

The above script will output: "3".



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