Home >Backend Development >PHP Tutorial >Detailed examples of the difference between PHP static variables and custom constants
php staticHow to use variablesand custom constants
⚑ Declaration and use of static variables
⚑ Customization How to use constants
What are static variables?
Static variables refer to variables declared with static. The difference between this type of variable and local variables is that when a static variable leaves its scope, its value will not automatically die. Continue to exist, and the most recent value can be retained when it is used next time.
The following example:
<?php function add() { static $i=0; $i++; echo $i; } add(); echo " "; add(); ?>
In this program, a function add() is mainly defined, and then add() is called twice.
If you use local variables to divide this code, the output should be 1 both times. But the actual output is 1 and 2.
This is because the variable i was added with a modifier static when it was declared, which means that the i variable is a static variable inside the add() function and has the function of memorizing its own value. When the first When we call add for the first time, i becomes 1 due to self-increment. At this time, i remember that it is no longer 0, but 1. When we call add again, i increments again and changes from 1 to 1. 2. From this, we can see the characteristics of static variables.
What are custom constants?
The so-called custom constant refers to using a character identifier to represent another object. This object can be a numerical value, a string, a Boolean value, etc. Its definition has many similarities with variables. The only difference is that the value of a variable can be changed arbitrarily while the program is running, but once a custom constant is defined, it can no longer be modified while the program is running.
The definition is as follows:
define("YEAR","2012");
Use the define keyword to bind the string 2012 to YEAR. It will be used wherever YEAR appears in the program. 2012 instead. Generally, when we define constants, the constant names use uppercase letters.
Example:
<?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. When we use When echo connects them to display, the difference from variables is that "$" is not used.
The result of its operation is: 2012-12-21 Doomsday.
The above is the detailed content of Detailed examples of the difference between PHP static variables and custom constants. For more information, please follow other related articles on the PHP Chinese website!