{PHP variable}

Source: Internet
Author: User
Tags http file upload null null parse error true true
#一, PHP variable definition: Variables are used to store values, such as numbers, text strings or arrays, V: string/integer/double/array/object

Naming rules:

1. The variable name of PHP is case-sensitive. 2. The variable name must begin with $3, the variable name can be underlined 4, the variable name cannot start with a numeric character
5. $this is a special variable that cannot be assigned to a value.
 
  

Assigning values to #二 and PHP variables

 
  

* Only a variable with a name can reference an assignment:

 
  

#变量默认值

Although it is not necessary to initialize variables in PHP, it is a good practice to initialize variables. Uninitialized variable has a default value of its type

-The default value for a variable of type Boolean is FALSE,

-The default value for shaping and floating-point variables is zero,

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

* Depending on the default value of the uninitialized variable, there may be problems in some cases, such as when one file is included in the other and the same variable name is encountered.

In addition to the php.in Register_globals Open is a major security risk. Using uninitialized variables emits a e_notice error.

But not when attaching a unit to an uninitialized array.

The isset () language structure can be used to detect 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 '; $unset _obj->shit = ' 234 '; Var_dump ($unset _obj); Var_export ($unset _obj);? >

#预定义变量

Warning

PHP 4.2.0 and subsequent versions, the default value of PHP directive register_globals is off. This is a major change in PHP. Letting the register_globals value off will affect the validity of the set of predefined variables at global scope. For example, in order to get the value of Document_root, you would have to use $_server[' document_root ' instead of $document_root, as in the case of a $_get[' id ') instead of $id from the URL/HTTP/ Get the ID value in www.example.com/test.php?id=3, or use $_env[' home ' instead of $HOME get the value of the environment variable HOME.

For more information, please read the Register_globals configuration entry, the use of register globals in the security chapter, and the release announcements for php»4.1.0 and»4.2.0.

If there are available PHP pre-defined variables that would be best used, such as hyper global arrays.

Starting with PHP 4.1.0, PHP provides an additional set of predefined arrays that contain data from the Web server (if available), the runtime environment, and user input. These arrays are very special and they take effect automatically in the global scope, for example, automatically in any scope. This is often referred to as an automatic global variable (autoglobals) or a Hyper global variable (superglobals). (There is no mechanism for users to customize hyper-global variables in PHP.) The hyper-global variables are listed below, but in order to get their content and further discussion about the predefined variables of PHP and their nature, see predefined variables. Also, you will notice that the old pre-defined array ($HTTP _*_vars) still exists. From PHP 5.0.0, use the Register_long_arrays setting option to disable the long type of PHP predefined variable array.

NOTE: variable variable

A super global variable cannot be used as a mutable variable.

Note:

Although hyper global variables and http_*_vars exist simultaneously. But they are not the same variable, so changing one value does not affect the other.

If the variables in some variables_order are not set, their corresponding PHP predefined arrays are also empty.

Predefined variables 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 information is represented as a return header. See FAQ "How does register_globals affect me?" "Table of Contents Super global variables?" A hyper-global variable is a built-in variable $globals that is always available in all scopes? Reference all variables available 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 variables
$_cookie? HTTP cookies$php_errormsg? Previous error message $http_raw_post_data? Native post data $http_response_header? HTTP response header $ARGC? The number of arguments passed to the script $argv? An array of arguments passed to the script


#可变变量

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

 
  

To use mutable variables with arrays, you must address an ambiguous question. This is when you write the $ $a [1], the parser needs to know that it wants to $a [1] as a variable,

Still want $ $a as a variable and take out the value of the variable indexed as [1]. The syntax for solving this problem is to use ${$a [1] for the first case, and ${$a}[1 for the second case).

#变量函数

Variable handling Function Array_key_exists

Table of Contents isset? Is the detection variable set unset? Release the given variable empty? Check if a variable is empty var_dump? Information about printing variables Var_export? Outputs or returns the string representation of a variable print_r? Print easy-to-understand information about variables. Serialize? Produces a settype that represents a value that can be stored? Set the type of the variable strval? Gets the string value of the variable unserialize? Create a PHP value is_null from a stored representation? is the detection variable null Is_array? Is the detection variable an array is_bool? Is the detection variable boolean-is_callable? Is the detection parameter a legitimate callable structure is_double? Is_float's alias Is_float? Is the detection variable a floating-point is_int? Is the detection variable an integer is_integer? Is_int's alias Is_long? Is_int's alias Is_numeric? Is the detection variable a numeric or numeric string is_object? Detects if a variable is an object is_real? Is_float's alias Is_resource? Is the detection variable a resource type is_scalar? Is the detection variable a scalar is_string? Detects if a variable is a string array_key_exists (mixed key, array search) to check if 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's alias Floatval? Get the floating-point value of a variable get_defined_vars? Returns an array of all the defined variables Get_resource_type? return resource (Resource) type GetType? Gets the type of the variable import_request_variables? Import the Get/post/cookie variable into the global scope intval? Gets the integer value of the variable

* Various data types function output comparison

              

Table p.1. Comparison expression of $x with PHP function GetType () empty () Is_null () isset () boolean:if ($x) $x = ""; String true false true false$x = NULL null true True false Falsevar $x; Null true True false false$x not yet defined NULL true true false false$x = array (); Array true FALSE true false$x = false; Boolean true FALSE true false$x = true; Boolean false false TRUE true$x = 1; Integer false false TRUE true$x = 42; Integer false false TRUE true$x = 0; Integer true FALSE true false$x =-1; Integer false false TRUE true$x = "1"; String false TRUE true$x = "0"; String True FALSE true false$x = "1"; String false TRUE true$x = "PHP"; String false True true$x = "true"; String false TRUE true$x = "false"; String False True True

#变量范围

Variable Range

              

The scope of a variable is the context in which it is defined (that is, its effective scope). Most PHP variables have a single range.

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

This script does not have any output, because the Echo statement refers to a local version of the variable $a, and within that range, it is not assigned a value.


In PHP, global variables must be declared as globals when used in functions. The
 
   output of the above script will be "3". The global variable $a and $b are declared in the function, and all reference variables of any variable are pointed to the global variable.


                  

The second way to access variables globally is to customize $GLOBALS arrays with special PHP. The previous example can be written as:


$GLOBALS is an associative array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the contents of the variable. $GLOBALS exists globally because $GLOBALS is a hyper-global variable. The following example shows the usefulness of a hyper-global variable: Example #3 Examples of hyper-global variables and scopes 
 
  


Static variable static variables are only present in the local function domain, but their values are not lost when the program executes away from the scope. Take a look at the following example:

Example #4 demonstrating the need for static variables

function Test ()
{
$a = 0;
echo $a;
$a + +;

+ + $a;
}

Test ();
?>

The value of $a is set to 0 and output "0".

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

To write a count function that does not lose this count value, define the variable $a as static:

Examples of Example #5 using static variables

function test ()
{
static $a = 0;
echo $a;
$a + +;

echo $a;
}

Test ();
?>

Now, the variable $ A is initialized at the first call to test (), and each call to the test () function outputs the value of the $a and adds one.

Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because they can be recursive indefinitely. You must ensure that there is sufficient method to abort the recursion. This simple function recursively counts to 10, using a 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 example above. If you assign a value to a declaration with the result of an expression, it causes a parse error.

Example #7 declaring 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;
}
?>

References to global and static variables

In Zend engine 1, it drives the PHP4, and the static and global definitions of variables are implemented in references way. For example, a real global variable imported with a global statement inside a function field actually establishes a reference to a global variable. This may lead to unexpected behavior, 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);
?>

Performing the above example will result in the following output:


Null
Object (StdClass) (0) {
}

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

function &get_instance_ref () {
Static $obj;

Echo ' Static object: ';
Var_dump ($obj);
if (!isset ($obj)) {
Assigning a reference 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)) {
Assigning an object to a static variable
$obj = new Stdclass;
}
$obj->property++;
return $obj;
}

$obj 1 = get_instance_ref ();
$still _obj1 = Get_instance_ref ();
echo "\ n";
$obj 2 = Get_instance_noref ();
$still _obj2 = Get_instance_noref ();
?>

Performing the above 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 example above demonstrates 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.

#扩展: [partly from the network]

 Definition (c description)://-----------------------------------------------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.   Values of various data types are acceptable.               Zend_uchar type;             PHP variable type Zend_uchar is_ref;            Whether to refer to Zend_uint refcount; Number of references}; The-----------------------------------------------(zend.h) struct zval is the PHP variable that is described. Second, Operation 1. Define a variable and assign a value. such as $a=1; The operation performed internally is approximately: ① defines a zval variable a. ② allocates memory for variable A and initializes it. ③ assigns a value to variable a.                                                                                             ④ 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: ② make_std_zval (ZV) \ Alloc_zval (ZV) is the specific action of this:                                                         \//Allocate memory init_pzval (ZV); Initialize #define ALLOC_ZVAL (z) \//Allocate memory Zend_fast_alloc (z, Zval, Zval_c ache_list) #define ZEND_FAST_ALLOC (p, type, fc_type) \ (p) = (type *) emalloc (sizeof (type)) #define EMALLOC (size) _emalloc (size) zend_file_line_cc zend_file_line_empty_cc) 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); Operation memory via C function} return _zend_mm_alloc_int (AG (mm_heap), size zend_file_line_relay_cc zend_file_line_orig_relay_cc); } #define INIT_PZVAL (z) \//initialization (z)->refcount = 1;                         \                   The number of references is 1 (z)->is_ref = 0; The variable is not referenced where the ④ is: first check whether the variable to be added already exists in the symbol table, if present, do not store, the corresponding RefCount plus one. If it does not exist, it is added behind the symbol table. You can view the macro definitions for zend_set_symbol_with_length in the zend_api.h file. 2. Assigns the value of a variable to another variable. such as: $a =1; $b = $a; The internal operation is about: Do not request new memory space, directly add the variable B into the symbol table, and then point to the memory space referred to in variable A. The refcount of the variable is added one. #define ZVAL_ADDREF (PZ) (+ + (PZ)->refcount). But each of the is_ref is 0. 3. unset a variable. such as $a=1; $b = $a; unset ($b); The internal operation is about: check whether the variable refcount is greater than 1, if more than 1, there are other variables are also concerned about this memory space, then the refcount minus one, that is, the # define ZVAL_DELREF (PZ) (--(PZ)->refcount )。 If equal to 1, the variable space is released directly, namely Free_zval (VAR). 4. A non-referenced two variable shares the same memory space when one is assigned to the new value. such as: $a =1; $b = $a; $b = 2; The operation performed internally is approximately: ① executes $a=1, and the is_ref of variable A is 0,refcount 1. ② executes the $b= $a; Is_ref changes to 0,refcount to 2. Variables A, B point to the same memory space ③ execute $b=2; When the is_ref is judged, if 0, the description is not referenced, then the split variable macro is called, the refcount is reduced by one, the variable is divided into new memory space, initialized, and the new value is assigned. If 1, the description is quoted and can be assigned 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_cto    R (* (PPZV)); \ (* (PPZV))->refcount=1; \ (* (PPZV))->is_ref = 0; \} \} 5. The two variables referenced, one of which is assigned a new value. such as: $a =1; $b =& $a; $b = 2; The operation performed internally is approximately: ① executes $a=1, and the is_ref of variable A is 0,refcount 1. ② executes the $b=& $a; Is_ref changes to 1,refcount to 2. ③ executes $b=2; When the is_ref is judged, the split variable macro is called if 0. If 1, the value is directly assigned.    #define Replace_zval_value (Ppzv_dest, pzv_src, copy) {\ int is_ref, refcount;  \ \ separate_zval_if_not_ref (ppzv_dest); \//Determine if the reference is being referenced and perform the appropriate action.   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 ①: such as $a=1; $b = $a; $c =& $a; The operation performed internally is approximately: ① executes $a=1; Is_ref is 0,refcount for 1. The ② executes the $b= $a, and Is_ref becomes 2 for 0,refcount. ③ execution of $c=& $a;B is separated and the memory space is re-divided. Variable A, C points to the space of the original variable A. The is_ref of variable B is 0,refcount to 1. The is_ref of variables A and C is 1,refcount 2. 7. Separation ②: such as $a=1, $b =& $a; $c = $a; The operation performed internally is approximately: ① executes $a=1; Is_ref is 0,refcount for 1. The ② executes the $b=& $a, and Is_ref becomes 2 for 1,refcount. ③ executes the $c= $a, the variable c is separated, the new space is divided, and the Is_ref is 0,refcount 1. The variable A and B keep the original reference unchanged, and the Is_ref is 1,refcount to 2. 8. The storage of global variables and local variables. Internally, there are a lot of hash tables, some are used to manage arrays, some manage objects, and two are used to manage PHP variables, one is a global variable hash table, and the other is a local variable hash table. Variables that need to be registered to the system, as long as the call Zend_set_symbol (EG (active_symbol_table), "local_variable", new_var1); (registered as a local variable) or Zend_set_symbol ( &eg (symbol_table), "global_variable", NEW_VAR2); (registered as a global variable). Hash table structure to view the zend_hash.h file. Attached: 1. The operation of the system core can be considered as much as possible to improve the execution efficiency of its operation. You can increase the speed of execution by substituting "multiline macro definition" instead of "no return value small function". Because the macro definition, is in the program compile, the macro body is replaced directly to the calling its corresponding macro name, eliminating the C language in the function call of a series of operations (such as: Save the current variable state, function related information into the stack, out of the stack and other operations). 2. In a compiled language, variables must be defined first and then used. The memory space is partitioned for all variables at compile time. In an interpreted language, the runtime uses a variable to apply the memory space. This eliminates the hassle of defining variables, but some of the hidden syntax errors can be found at run time. 3. When working with memory, you can consider reducing the use of memory as much as possible. such as $a=1; $b = $a;. Internal operations actually simply point the variable A and B to the same memory area. The benefits of doing so can save memory on the one hand, and on the other, reduce the operating procedures and improve the execution speed of the system. Because it eliminates the need to request memory space, initialization, assignment of some operations, but simply to add the variable B to the symbol table, and point to a refers to the memory area. When necessary, the memory area of the variable A and B is separated. If you encounter $b=2;. 4. There are some doubts about the place. ① according to the aboveDefined PHP variable struct zval, when we define a long variable, it is supposed that the value of the "type" member inside the variable should be long, and the range of the number that can be stored is: (4 bytes) -2^31+1~2^31. When a PHP variable is actually defined and assigned a value, it is found that when a range of long can be represented, it is automatically converted to double. The ②double type is 8 bytes and can be stored in a range of: -2^63+1~2^63. When actually defining a PHP variable and assigning a value, it is found that it can represent more than 1.0E+260 of the number. This already exceeds the range that double can represent. I suspect that there should be a program segment dedicated to dealing with variable type conversions and expanding the data storage capabilities of variables. It seems to be a pan-type, not very well-understood. But I didn't find the relevant program section.  Conclusion: Using PHP variables, you can not worry too much about the data overflow problem of variables.

#

  • Related Article

    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.