wordpress CMS主题 微信
Home > 网站建设 > The global variables, local variables and static variables

The global variables, local variables and static variables

高时银博客 网站建设 点击: 1,593 次 0 0

We talked about several kinds of variables: bool variables, int, string, floating-point variable. This section again from variable function variables: talk aboutglobal variables, local variables and static variables. (hint: PHP variable names are case sensitive, and other such as the class name and function name is notcase sensitive)

1, global variables.

Global variables are also known as external variables, it is in the function of external variables defined. It does not belong to a function, it belongs to a source file. The scope is from the end of the definition of the variables of the position to the source file. The function of PHP to call global variables in two ways: (1) and global in the variable; (2) use a global array GLOBAL["variable name"]. The following example can learn how to use global variables:

<?php$a=99;$b=88;function table()


gLobal $a; / / to call global variables through the global keyword

$GLOBALS['b']=188; / / to call global variables through super global array, and change the value of $b is 188;

$a=100; the value of the variable $a to 100;

//      $b=188;


table(); / / call the function

Echo $a; / / $a output value

Echo "<br>";

Echo $b; / / $b output value


Results: 100188

2, the local variable.

The example above, if you do not use the global keyword and a global array, but directly change the function values of the variables, then the function of thevariables into a local variable, that is to say the function ends, these variableswere released, does not exist. So, it affects global variables can not define the start value of. Then, the output is the original value: 9988. That is to say, local variables are out of function, it will not work.

3, static variables.

Static variables exist only in the function domain, that is to say, the static variables only survived in the stack. The general function of internal variables will be released after the function exits, such as local variables, static variables, butnot. That is to say, the next time you call to this function, the value of the variablewill be retained. As long as with the keyword static variable, the variable becomes a static variable. Below, I do under the illustrated by a small example:

<?phpfunction table(){Static $a=0; / / define a static variable, and the value 0;

Echo $a; / / the first output variable

Echo "<br>";

$a++; / / and since 1







The output result is: 0123. If not defined as static, then each output will be 0, that is because in self ago output variable values.

版权所有 © 转载时必须以链接形式注明作者和原始出处!