PHP static variables and the use of custom constants

  • 2020-03-31 20:15:35
  • OfStack

The & # 9873; Declaration and use of static variables
The & # 9873; Customize the way constants are used

What is a static variable?
A static variable is a variable that is declared static. The difference between this type of variable and a local variable is that when a static variable leaves its scope, its value will not automatically die, but will continue to exist.
Here are some examples:
 
<?php 
function add() 
{ 
static $i=0; 
$i++; 
echo $i; 
} 
add(); 
echo " "; 
add(); 
?> 

In this program, a function called add() is defined and then called twice.
If you were to divide the code in terms of local variables, the output would be 1 both times. But the actual output is 1 and 2.
This is because the variable I in statement a modifier are being added to the static, it marks the I variable within the add () function is a static variable, have the function that memory itself value, when the first call to add, I since they add into 1, this time, I remember myself no longer is 0, 1, but when we call the add again, I once again since, from 1 to 2. From this, we can see the characteristics of static variables.
What are custom constants?
A custom constant is a character identifier that represents another object, which can be a value, a string, a Boolean, and so on. Its definition has many similarities with variables. The only difference is that the values of variables can be changed as the program runs, while custom constants, once defined, cannot be changed while the program runs.
The definition is as follows:
Define (" YEAR ", "2012");
Use the define keyword to bind the 2012 string to the YEAR, and then replace the YEAR in the program with 2012. In general, when we define constants, we use capital letters for constant names.
Ex. :
 
<?php 
define("YEAR","2012"); 
define("MONTH","12"); 
define("DATE","21"); 
define("THING","Doomsday"); 
echo YEAR."-".MONTH."-".DATE." ".THING; 
?> 

In this program, four constants are defined, namely YEAR, MONTH, DATE and THING. Their corresponding values are 2012,12,21 and Doomsday respectively. When we use echo to connect them and display them, the difference with the variable is that "$" is not used.
The result of its operation is: 2012-12-21 Doomsday.

Related articles: