The unset function is a built-in function for php to destroy variables. we introduced how to use unset to destroy static variables and global variables, and how to destroy array variables. let's look at the example below.
The unset function is a built-in function for php to destroy variables. we introduced how to use unset to destroy static variables and global variables, and how to destroy array variables. let's look at the example below.
Example 1. unset () example
The instance code is as follows:
- // 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 instance code is as follows:
- 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 instance code is as follows:
- Function foo (& $ bar ){
- Unset ($ bar );
- $ Bar = "blah ";
- }
- $ Bar = 'something ';
- Echo "$ barn ";
- Foo ($ bar );
- Echo "$ barn ";
- ?>
The above example will output:
Something
Something
Unset () static variables. Strictly speaking, the use of unset () to destroy static variables only disconnects the reference between the variable name and the variable value.
Example:
- 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
#######################
The unset () global variable is the same as the unset () static variable. If unset () is a global variable in the function, only the local variable is destroyed, the variables in the call environment will remain the same value before the call of unset.
Try to compare the following two examples:
The instance code is as follows:
- Function destroy_foo (){
- Global $ foo;
- Unset ($ foo );
- }
- $ Foo = 'bar ';
- Destroy_foo ();
- Echo $ foo;
- ?>
-
- 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.