Usage examples of php static variables and custom constants

WBOY
Release: 2016-07-25 08:52:37
Original
800 people have browsed it
  1. function add()
  2. {
  3. static $i=0;
  4. $i++;
  5. echo $i;
  6. }
  7. add();
  8. echo " ";
  9. add();
  10. ?>
Copy code

defines a function add(), and then calls add() 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 add is called for the first time At this time, i becomes 1 due to self-increment. At this time, i remember that it is no longer 0, but 1. When add is called again, i increases itself again and changes from 1 to 2. From this, we can see the characteristics of static variables.

Reference link: Simple example of php static variables Detailed explanation of the usage of php static static variable modifiers

Part 2, 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 difference is that the value of the variable can be changed arbitrarily while the program is running, but once the custom constant is defined, it can no longer be modified while the program is running.

Definition method: define("YEAR","2012"); Use the define keyword to bind the string 2012 to YEAR. In the future, wherever YEAR appears in the program, 2012 will be used instead. Generally, when defining constants, use uppercase letters for constant names.

Example, php custom constant.

  1. define("YEAR","2012");
  2. define("MONTH","12");
  3. define("DATE","21");
  4. define(" THING","Doomsday");
  5. echo YEAR."-".MONTH."-".DATE." ".THING;
  6. ?>
Copy code

defines four constants, namely YEAR, MONTH, DATE, THING, the corresponding values ​​are 2012, 12, 21, Doomsday respectively. When they are connected and displayed using echo, the difference from variables is that "$" is not used. operation result: 2012-12-21 Doomsday.



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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!