Home > Backend Development > PHP Tutorial > Introduction to php variable scope

Introduction to php variable scope

高洛峰
Release: 2023-03-02 19:04:01
Original
1111 people have browsed it

For example:
Copy the code The code is as follows:
$a = 1;
include 'b.inc';
?>

The variable $a here will take effect in the included file b.inc. However, in user-defined functions, a local function scope will be introduced. Any variables used inside a function will be limited to the scope of the local function by default and are local variables at this time.
 
  Global variables in PHP must be declared global when used in functions.
  Variables declared using global in a function are global variables and can be used outside the function. Note: When declaring a variable globally, you cannot directly assign a value to the variable. You need to declare it first and then assign a value.

  In the global scope, global variables can also be accessed through $GLOBALS. There is no need to use the global keyword to access global variables within a function. $GLOBALS is an associative array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the variable's content. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable.
 Constants can be defined and accessed anywhere regardless of the scope of the variable;

 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. Static variables are only initialized on the first call. They can be assigned values ​​when declared, but cannot be expression values. Assigning it with the result of an expression in a declaration will result in a parsing error.

  When a reference (variable or object with &) is assigned to a static variable, the reference is not stored statically, and the value of the static variable is not remembered when the function is called for the second time. Similarly, when a reference (variable or object with &) is assigned to a global variable, the change of this variable has no effect outside the function, and the scope is only within the function.

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template