Home > Backend Development > PHP Tutorial > Introduction to PHP variable scope_PHP tutorial

Introduction to PHP variable scope_PHP tutorial

WBOY
Release: 2016-07-21 15:14:41
Original
900 people have browsed it

For example:

Copy code The code is as follows:

$a = 1;
include 'b.inc';
?>

Here variable $a 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 as 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 variable). 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 (a 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 the second time the function is called. 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326212.htmlTechArticleFor example: Copy the code as follows: ?php $a = 1; include 'b.inc'; ? Variables here $a will take effect in the include file b.inc. However, in a user-defined function, a local function scope...
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