unsetFunction is a function that comes with PHP to destroy variables. We introduced the method of using unset to destroy static variables and global variables. At the same time, we also introduced the method of destroying array variables. , let’s look at examples below.
Example 1. unset() Example
<?php // 销毁单个变量 unset ($foo); // 销毁单个数组元素 unset ($bar['quux']); // 销毁一个以上的变量 unset ($foo1, $foo2, $foo3); ?>
The behavior of unset() in the function will vary depending on the type of variable you want to destroy.
If you unset() a global variable in a function, only the local variable will be destroyed, and the variables in the calling environment will maintain the same value before calling unset().
<?php function destroy_foo() { global $foo; unset($foo); } $foo = ‘bar’; destroy_foo(); echo $foo; ?>
The above example will output:
bar
If you unset() a variable passed by reference in the function, it will only be a local variable is destroyed, and the variables in the calling environment will retain the same value before calling unset().
<?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, use unset() to destroy static variables, just The reference between variable name and variable value is broken.
Example:
<?php function foo() { static $b; $a++; $b++; echo "$a---$bn"; unset($a,$b); var_dump($a); var_dump($b); echo "######################n"; } foo(); foo(); foo(); ?>
Run this example, output:
1---1 NULL NULL ####################### 1---2 NULL NULL ####################### 1---3 NULL NULL #######################
unset() global variable
The same as unset() static variable, if unset() in the function ) a global variable, only the local variable is destroyed, and the variables in the calling environment will maintain the same value before calling unset().
Try to compare the following two examples:
<?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; ?>
Running the first example will output: bar, while the second example will not output anything.
The above is the detailed content of Detailed explanation of how to use the unset() function to destroy single or multiple variable instances. For more information, please follow other related articles on the PHP Chinese website!