PHP variable scope, PHP global variables and static variables

WBOY
Release: 2016-07-25 08:52:38
Original
1037 people have browsed it
  1. $a = 1;
  2. include 'b.inc';
  3. ?>
Copy code

Here variable $a will take effect in the include file b.inc. 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. PHP global variables 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 it.

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. PHP static variables only exist in the local function scope, but their values are not lost when the 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. Simple example of php static variables 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.



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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!