Example 1. unset () example
The code is as follows: |
Copy code |
<? Php // Destroy a single variable Unset ($ foo ); // Destroy a single array element Unset ($ bar ['quux ']); // Destroy more than one variable Unset ($ foo1, $ foo2, $ foo3 ); ?> |
The action of unset () in a function varies depending on the type of the variable to be destroyed.
If unset () is a global variable in the function, only the local variable is destroyed, and the variables in the call environment will keep the same value before the call of unset.
The code is as follows: |
Copy code |
<? Php Function destroy_foo (){ Global $ foo; Unset ($ foo ); } $ Foo = 'bar '; Destroy_foo (); Echo $ foo; ?> |
The above example will output:
Bar
If unset () is a variable passed by reference in the function, only the local variable is destroyed, and the variables in the call environment will keep the same value before the call of unset.
The code is as follows: |
Copy code |
<? Php Function foo (& $ bar ){ Unset ($ bar ); $ Bar = "blah "; } $ Bar = 'something '; Echo "$ barn "; Foo ($ bar ); Echo "$ barn "; ?> The above example will output: Something Something |
Unset () static variable
Strictly speaking, the use of unset () to destroy static variables only disconnects the reference between the variable name and the variable value.
Example:
The code is as follows: |
Copy code |
<? Php Function foo (){ Static $ B; $ A ++; $ B ++; Echo "$ a --- $ bn "; Unset ($ a, $ B ); Var_dump ($ ); Var_dump ($ B ); Echo "###################### n "; } Foo (); Foo (); Foo (); ?> Run this example and output: 1---1 NULL NULL ####################### 1---2 NULL NULL ####################### 1---3 NULL NULL ####################### |
Unset () global variable
Like the unset () static variable, if unset () is a global variable in the function, only the local variable is destroyed, and the variable in the call environment will keep calling unset () the same value.
Try to compare the following two examples:
The code is as follows: |
Copy code |
<? Php Function destroy_foo (){ Global $ foo; Unset ($ foo ); } $ Foo = 'bar '; Destroy_foo (); Echo $ foo; ?> <? Php Function destroy_foo (){ Global $ foo; Unset ($ GLOBALS ['foo']); } $ Foo = 'bar '; Destroy_foo (); Echo $ foo; ?> |
The first example will output bar, while the second example will not have any output.