Introduction to the php variable scope

  • 2020-05-26 08:02:04
  • OfStack

Such as:
 
<?php 
$a = 1; 
include 'b.inc'; 
?> 

Here the variable $a will take effect in the include file b.inc. However, in user-defined functions, a local function scope is introduced. Any variables used within a function are, by default, limited to local functions, which are local variables.

Global variables in PHP must be declared as global when used in a function.
Variables declared using global in a function are global variables that can be used outside of a function. Note: when global declares a variable, it is not possible to assign a value to the variable directly.

Global variables can also be accessed from $GLOBALS at the global level, instead of using the global keyword within the function. $GLOBALS is an associative array with 1 element for each variable. The key name corresponds to the variable name, and the value corresponds to the content of the variable. $GLOBALS exists globally because $GLOBALS is a super global variable.
Constants can be defined and accessed anywhere regardless of the scope of a variable;

Another important feature of variable scopes is static variables (static variable). Static variables exist only in the local function domain, but their values are not lost when program execution leaves this scope. Static variables are initialized only on the first call and can be assigned a value when declared, not an expression value. Assigning the result of an expression to it in a declaration results in a parsing error.

When taking a reference (take it with you & When assigning a value to a static variable, the reference is not statically stored, and the value of the static variable is not remembered the second time the function is called. Also, when you take a reference (take it with you & When assigning a value to the global variable, changes to this variable do not apply outside the function, but only within the function.

Related articles: