{Php variable}

Source: Internet
Author: User
{Php variable} #1. PHP variable definition: variables are used to store values, such as numbers, text strings or arrays, and five-medium: string/integer/double/array/object

Naming rules:

1. PHP variable names are case sensitive. 2. the variable name must start with $. 3. the variable name can start with an underscore. 4. the variable name cannot start with a number.
5. $ this is a special variable and cannot be assigned a value.
 

# Assignment of php variables

 

* Only variables with names can reference values:

 

# Default variable values

Although you do not need to initialize variables in PHP, it is a good habit to initialize variables. Uninitialized variables have default values of their types.

-The default value of a Boolean variable is FALSE,

-The default value of integer and floating point variables is zero,

-The default value of a string variable is null, or the default value of an array variable is an empty array.

* Dependency on the default value of uninitialized variables may cause problems in some cases. for example, when a file is included in another, the same variable name may occur.

Opening php. in register_globals is a major security risk. An E_NOTICE error occurs when uninitialized variables are used,

But not when appending a cell to an uninitialized array.

The isset () language structure can be used to check whether a variable has been initialized.

              

25var_dump ($ unset_int); // Float/double usage; outputs 'float (1.25) '$ unset_float + = 1.25; var_dump ($ unset_float); // Array usage; outputs array (1) {[3] => string (3) "def"} $ unset_arr [3] = "def"; // array () + array (3 => "def") => array (3 => "def") var_dump ($ unset_arr); // Object usage; creates new stdClass object // Outputs: object (stdClass) #1 (1) {["foo"] => string (3) "bar"} $ unset_obj-> foo = 'bar'; $ uns Et_obj-> shit = '000000'; var_dump ($ unset_obj); var_export ($ unset_obj);?>

# Predefined variables

Warning

In PHP 4.2.0 and later versions, the default value of the PHP command register_globals is off. This is a major change in PHP. Setting the value of register_globals to off affects the validity of the predefined variable set within the global range. For example, to obtain the DOCUMENT_ROOT value, you must use $ _ SERVER ['document _ root'] instead of $ DOCUMENT_ROOT, as shown in the following figure, use $ _ GET ['id'] instead of $ id from URL http://www.example.com/test.php? In id = 3, get the id value, or use $ _ ENV ['home'] instead of $ HOME to get the value of the environment variable HOME.

For more information, see register_globals configuration items, use Register Globals in the security Chapter, and publish announcements for PHP» 4.1.0 and» 4.2.0.

If there are available PHP pre-defined variables, it is best to use them, such as ultra-Global arrays.

Starting from PHP 4.1.0, PHP provides an additional set of pre-defined arrays that contain data from the web server (if available), runtime environment, and user input. These arrays are very special and they take effect globally, for example, automatically within any range. Therefore, it is usually called autoglobals or superglobals ). (PHP does not have a mechanism for customizing global variables .) Hyperglobal variables are listed below. For more information about them, PHP predefined variables, and their nature, see predefine variables. In addition, you will also notice that the old pre-defined array ($ HTTP _ * _ VARS) still exists. From PHP 5.0.0, you can use register_long_arrays to disable long PHP pre-defined variable arrays.

Note: variable

Super global variables cannot be used as variable variables.

Note:

Although the hyperglobal variable and HTTP _ * _ VARS both exist. But they are not the same variable, so changing one value does not affect the other.

If some variables in variables_order are not set, their corresponding PHP pre-defined arrays are also empty.

For all scripts, PHP provides a large number of predefined variables. These variables represent all external variables as built-in environment variables and the error message as the return header. See the FAQ "What is the impact of register_globals on me ?" Table of Contents Super global variable? Hyperglobal variables are always available built-in variables in all scopes $ GLOBALS? Reference all available variables in the global scope $ _ SERVER? Server and execution environment information $ _ GET? Http get variable $ _ POST? Http post variable $ _ FILES? HTTP file Upload variable $ _ REQUEST? HTTP Request variable $ _ SESSION? Session variable $ _ ENV? Environment variable
$ _ COOKIE? HTTP Cookies $ php_errormsg? Previous error message $ HTTP_RAW_POST_DATA? Native POST data $ http_response_header? HTTP response header $ argc? Number of parameters passed to the script $ argv? Parameter array passed to the script


# Variable

Sometimes it is convenient to use a variable name. That is to say, the variable name of a variable can be dynamically set and used.

 

To use variables in an array, you must solve an ambiguous problem. When writing $ a [1], the parser needs to know that $ a [1] is used as a variable,

You still want $ a as a variable and retrieve the value of [1] in the variable. The syntax for solving this problem is to use $ {$ a [1]} for the first case and $ {$ a} [1] for the second case.

# Variable functions

Variable handling function array_key_exists

Table of Contents isset? Check whether the variable is set to unset? Release the given variable empty? Check whether a variable is empty var_dump? Print information about the variable var_export? Output or return a variable string that represents print_r? Print easy-to-understand information about variables. Serialize? Generate a value that can be stored as settype? Set the variable type strval? Get the variable's string value unserialize? Create the PHP value is_null from the stored representation? Check whether the variable is NULL is_array? Check whether the variable is an array is_bool? Check whether the variable is Boolean is_callable? Check whether the parameter is a valid is_double structure? Is_float alias is_float? Check whether the variable is a floating-point is_int? Check whether the variable is an integer is_integer? Is_int alias is_long? Is_int alias is_numeric? Check whether the variable is a number or number string is_object? Check whether the variable is an object is_real? Is_float alias is_resource? Is the check variable of the resource type is_scalar? Check whether the variable is a scalar is_string? Check whether the variable is a string array_key_exists (mixed key, array search). check whether the given key name or index exists in the array debug_zval_dump? Dumps a string representation of an internal zend value to output doubleval? Floatval alias floatval? Get the floating point value of the variable get_defined_vars? Returns the get_resource_type array consisting of all defined variables? Returns the resource type gettype? Get the variable type import_request_variables? Import GET/POST/Cookie variables to the global scope intval? Returns the integer of a variable.

* Function output comparison of various data types

              

Table P.1. comparison expression gettype () empty () is_null () isset () boolean: if ($ x) $ x = ""; string true false $ x = null true false FALSEvar $ x; null true false $ x not defined null true false $ x = array (); array true false $ x = false; boolean true false $ x = true; boolean false true $ x = 1; integer false true $ x = 42; integer false true $ x = 0; integer true false $ x =-1; integer false true $ x = "1 "; string false true $ x = "0"; string true false $ x = "-1"; string false true $ x = "php "; string false true $ x = "true"; string false true $ x = "false"; string FALSE TRUE

# Variable range

Variable range

              

The scope of a variable is the context defined by it (that is, its effective range ). Most PHP variables have only one separate range.

This separate range span also contains the files introduced by include and require. For example: Here the variable $ a will take effect in the included file B. inc:

This script does not have any output, because the echo statement references a local version of variable $ a and is not assigned a value within this range.


Global variables in PHP must be declared as global when used in functions.
 The output of the above script is "3 ". Specify the global variables $ a and $ B in the function. all referenced variables of any variable point to the global variable.


                  

The second way to access variables globally is to use a special PHP custom $ GLOBALS array. The preceding example can be written as follows:


$ GLOBALS is an associated array. each variable is an element. The key name corresponds to the variable name and the value corresponds to the variable content. $ GLOBALS exists globally because $ GLOBALS is a super global variable. The following Example shows how to use a hyperglobal variable: Example #3. Examples of hyperglobal variables and scopes
  


Static variables static variable static variables exist only in the local function domain, but their values are not lost when the program runs out of this scope. Take a look at the following example:

Example #4 demonstrate examples of static variables

Function Test ()
{
$ A = 0;
Echo $;
$ A ++;

// + + $;
}

Test ();
?>

Set $ a to 0 and output "0 ".

Adding $ a ++ to the variable does not work, because $ a does not exist once you exit this function.

To write a counting function that does not lose the current count value, you must define variable $ a as static:

Example #5 examples of using static variables

Function test ()
{
Static $ a = 0;
Echo $;
$ A ++;

Echo $;
}

Test ();
?>

Now, variable $ a is initialized when test () is called first. every time you call the test () function, the value of $ a is output and added with one.

Static variables also provide a method for processing recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because infinite recursion may occur. Make sure there are sufficient methods to abort recursion. The simple function calculates 10 recursively and uses the static variable $ count to determine when to stop:

Example #6 static variables and recursive functions

Function test ()
{
Static $ count = 0;

$ Count ++;
Echo $ count;
If ($ count <10 ){
Test ();
}
$ Count --;
}
?>

Note:

Static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs.

Example #7 declare static variables

Function foo (){
Static $ int = 0; // correct
Static $ int = 1 + 2; // wrong (as it is an expression)
Static $ int = sqrt (121); // wrong (as it is an expression too)

$ Int ++;
Echo $ int;
}
?>

Reference of global and static variables

In the first generation of Zend engine, it drives PHP4, and the static and global definitions of variables are implemented in the form of references. For example, a real global variable imported using a global statement within a function domain is actually a reference to a global variable. This may lead to unexpected behaviors, as demonstrated in the following example:

Function test_global_ref (){
Global $ obj;
$ Obj = & new stdclass;
}

Function test_global_noref (){
Global $ obj;
$ Obj = new stdclass;
}

Test_global_ref ();
Var_dump ($ obj );
Test_global_noref ();
Var_dump ($ obj );
?>

Executing the preceding example will result in the following output:


NULL
Object (stdClass) (0 ){
}

Similar behavior applies to static statements. References are not stored statically:

Function & get_instance_ref (){
Static $ obj;

Echo 'static object :';
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign a reference value to a static variable
$ Obj = & new stdclass;
}
$ Obj-> property ++;
Return $ obj;
}

Function & get_instance_noref (){
Static $ obj;

Echo 'static object :';
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign an object to a static variable
$ Obj = new stdclass;
}
$ Obj-> property ++;
Return $ obj;
}

$ Obj1 = get_instance_ref ();
$ Still_obj1 = get_instance_ref ();
Echo "\ n ";
$ Obj2 = get_instance_noref ();
$ Still_obj2 = get_instance_noref ();
?>

Executing the preceding example will result in the following output:


Static object: NULL
Static object: NULL

Static object: NULL
Static object: object (stdClass) (1 ){
["Property"] =>
Int (1)
}

The preceding example shows that when a reference is assigned to a static variable, the value of the second call to the & get_instance_ref () function is not remembered.

# Extension: [part from Network]

I. definition (c description): // define typedef struct _ zval_struct zval; typedef union _ zvalue_value {long lval; double dval; struct {char * val; int len;} str; hashTable * ht; zend_object_value obj;} zvalue_value; struct _ zval_struct {zvalue_value value; // php variable value, Union type. Accept values of various data types. Zend_uchar type; // php variable type zend_uchar is_ref; // whether to reference zend_uint refcount; // number of references}; // --------------------------------------- (z. end. h) the structure zval is the php variable described. 2. operation 1. Define a variable and assign values. For example, $ a = 1; the internal operation is roughly: ① define a zval variable. ② Allocate memory for variable a and initialize it. ③ Assign a value to variable. ④ Add variable a to the symbol table // ------------------------------------------------- zval * a; // ① MAKE_STD_ZVAL (a); // ② ZVAL_LONG (a, 1 ); // ③ ZEND_SET_SYMBOL (EG (active_symbol_table), "local_variable", a); // ④ // Note: ② specific operation is: # define MAKE_STD_ZVAL (zv) \ ALLOC_ZVAL (zv); \\// allocate memory INIT_PZVAL (zv); // Initialization # define ALLOC_ZVAL (z) \ // allocate memory ZEND_FAST_ALLOC (z, zval, ZVAL_CACHE_LIST) # de Fine ZEND_FAST_ALLOC (p, type, fc_type) \ (p) = (type *) emalloc (sizeof (type) # define emalloc (size) _ emalloc (size) ZEND_FILE_LINE_CC limit) ZEND_API void * _ emalloc (size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) {TSRMLS_FETCH (); if (UNEXPECTED (! AG (mm_heap)-> use_zend_alloc) {return malloc (size); // use the c function to operate memory} return _ zend_mm_alloc_int (AG (mm_heap), size ZEND_FILE_LINE_RELAY_CC callback );} # define INIT_PZVAL (z) \ // Initialization (z)-> refcount = 1; // The number of references is 1 (z)-> is_ref = 0; // the specific operation of variable 4 is not referenced: first, check whether the variable to be added already exists in the symbol table. If yes, it is not stored and add the corresponding refcount to one. If it does not exist, it is added after the symbol table. You can view the macro definition of ZEND_SET_SYMBOL_WITH_LENGTH in the zend_API.h file. 2. Assign the value of a variable to another variable. For example: $ a = 1; $ B = $ a; the internal operation is probably: directly add variable B to the symbol table without applying for a new memory space, then point to the memory space referred to by variable. Add the refcount of the variable to one. # Define ZVAL_ADDREF (pz) (++ (pz)-> refcount ). The is_ref values are both 0. 3. Unset a variable. For example, $ a = 1; $ B = $ a; unset ($ B); the internal operation is probably: Check whether the refcount of the variable is greater than 1. if it is greater than 1, note that there are other variables that are also focusing on the memory space. then, reduce refcount by one, that is, # define ZVAL_DELREF (pz) (-- (pz)-> refcount ). If it is equal to 1, the variable space is directly released, that is, FREE_ZVAL (var ). 4. Two variables that are not referenced share the same memory space when one of them is assigned a new value. For example: $ a = 1; $ B = $ a; $ B = 2; the internal operation is roughly: ① after $ a = 1 is executed, the is_ref of variable a is 0, and the refcount is 1. ② After $ B = $ a is executed, is_ref is changed to 0, and refcount is changed to 2. Variables a and B point to the same memory space ③ When $ B = 2 is executed, the is_ref is first judged. if the value is 0, it indicates that the variable is not referenced, the macro of separation variable is called, reduce refcount by one, divide the new memory space for the variable, initialize the variable, and add new values. If the value is 1, it indicates that there is a reference. you can assign a value directly. # Define SEPARATE_ZVAL_IF_NOT_REF (ppzv) \ if (! PZVAL_IS_REF (* ppzv) {\ SEPARATE_ZVAL (ppzv); \}# define SEPARATE_ZVAL (ppzv) \ {\ zval * orig_ptr = * (ppzv ); \ if (orig_ptr-> refcount> 1) {\ orig_ptr-> refcount --; \ ALLOC_ZVAL (* (ppzv); \ ** (ppzv) = * orig_ptr; \ zval_copy_ctor (* (ppzv); \ (* (ppzv)-> refcount = 1; \ (* (ppzv)-> is_ref = 0; \}\} 5. Two variables referenced, one of which is assigned a new value. For example: $ a = 1; $ B = & $ a; $ B = 2; the internal operation is roughly: ① after $ a = 1 is executed, the is_ref of variable a is 0, and the refcount is 1. ② After $ B = & $ a; is executed, is_ref is changed to 1, and refcount is changed to 2. ③ Execute $ B = 2. first, Judge is_ref. if it is 0, call the separation variable macro. If the value is 1, the value is assigned directly. # Define REPLACE_ZVAL_VALUE (ppzv_dest, pzv_src, copy) {\ int is_ref, refcount; \ SEPARATE_ZVAL_IF_NOT_REF (ppzv_dest); \ // determines whether the object is referenced and performs the corresponding operations. Is_ref = (* ppzv_dest)-> is_ref; \ refcount = (* ppzv_dest)-> refcount; \ zval_dtor (* ppzv_dest); \ ** ppzv_dest = * pzv_src; \ if (copy) {\ zval_copy_ctor (* ppzv_dest) ;\}\ (* ppzv_dest)-> is_ref = is_ref; \ (* ppzv_dest)-> refcount = refcount; \} 6. Separation ①: for example, $ a = 1; $ B = $ a; $ c = & $ a; after the internal operation is executed, is_ref is 0, and refcount is 1. ② After $ B = $ a is executed, is_ref is 0, and refcount is changed to 2. ③ When $ c = & $ a; is executed, variable B is separated and the memory space is re-divided. Variables a and c point to the space of the original variable. The is_ref of variable B is 0, and refcount is 1. The is_ref of the variables a and c is 1, and the refcount is 2. 7. Separation ②: for example, $ a = 1; $ B = & $ a; $ c = $ a; after the internal operation is executed, is_ref is 0, and refcount is 1. ② After $ B = & $ a; is executed, is_ref is 1, and refcount is changed to 2. ③ When $ c = $ a is executed, variable c is separated and the new space is divided. is_ref is 0, and refcount is 1. Variables a and B remain unchanged. is_ref is 1 and refcount is 2. 8. Storage of global and local variables. Internally, there are many hash tables, some of which are used to manage arrays, some are used to manage objects, and two are used to manage php variables. one is the global variable hash table, one is a local variable hash table. To register a variable with the system, you only need to call ZEND_SET_SYMBOL (EG (active_symbol_table), "local_variable", new_var1); (register as a local variable) or ZEND_SET_SYMBOL (& EG (symbol_table ), "global_variable", new_var2); (register as a global variable ). You can view the zend_hash.h file in the hash table structure. Appendix: 1. To improve the execution efficiency of the system's core operations, you can try to improve the operating efficiency. For example, you can replace "multi-row macro definition" with "No returned small function" to increase the execution speed. The macro definition replaces the macro directly with the corresponding macro name during program compilation, saving a series of operations on function calling in C language (for example, saving the current variable status, function-related operations such as Stack loading and out ). 2. In compiled languages, variables must be defined first and then used. Memory space is allocated for all variables during compilation. In interpreted language, the memory space is applied only when variables are used during runtime. This saves the trouble of defining variables, but some hidden syntax errors can only be detected at runtime. 3. When operating the memory, try to reduce the memory usage. For example, $ a = 1; $ B = $ ;. Internal operations only point variables a and B to the same memory area. The benefits of doing so can save memory on one hand, and reduce operation steps to improve the execution speed of the system. This saves some operations for applying for memory space, initializing, and assigning values, but simply adds variable B to the symbol table and points it to the memory area referred to by. When necessary, the memory areas of variables a and B are separated. In case of $ B = 2 ;. 4. Some questions. ① According to the above-defined php variable structure zval, when we define a long variable, the value of the "type" member inside the variable should be long, in addition, the range of data that can be stored is: (4 bytes)-2 ^ 31 + 1 ~ 2 ^ 31. When a php variable is defined and assigned a value, it is found that when the value exceeds the range expressed by long, it is automatically converted to double. ② The double type is 8 bytes and can be stored in the range of-2 ^ 63 + 1 ~ 2 ^ 63. When a php variable is actually defined and assigned a value, it is found that the number of representation exceeds 1.0E + 260. This is beyond the range that double can represent. I guess there should be a program segment specifically used to process the conversion of variable types and expand the data storage capability of variables. This seems to be a generic type, not quite understandable. However, I did not find the relevant program segment. Conclusion: using php variables does not have to worry too much about the data overflow of variables.

#

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.