PHP unset () function Detailed

When you want to destroy a variable, you can use unset () function to achieve.

grammar

void unset ( mixed $var [, mixed $... ] )
可以同时销毁多个变量

Parameter Description:

$ Var: variable to be destroyed.

return value

No return value.

Examples

<?php
<?php
// 销毁单个变量
$foo=123;
var_dump( $foo);
unset ($foo);
var_dump ($foo);
echo "<br />";
// 销毁单个数组元素
$bar=['quux'];
var_dump ($bar);
unset ($bar);
var_dump ($bar); 
echo "<br />";
// 销毁一个以上的变量
unset($foo1, $foo1, $foo3);
?>

Output

int(123) 
NULL 
array(1) { [0]=> string(4) "quux" } 
NULL 

Special needs where noted:

  • If the function unset () a global variable, only the local variable is destroyed. The variable in the calling environment will remain call the unset () before the same value.

Examples


<?php
function destroy_foo() {
    global $foo;//global是起传递参数的作用,而并非使变量的作用域为全局。
    //不能在用global声明变量的同时给变量赋值
    unset($foo);//销毁了函数内部的$foo变量
    var_dump($foo);//检查是否被销毁
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

The output is:

NULL  bar
  • If you want to unset the function () a global variable, you can use the $ GLOBALS array to achieve:

Examples

<?php
function foo() 
{
    unset($GLOBALS['bar']);
}
 
$bar = "something";
foo();
var_dump($bar);//检查是否被销毁
?>

Output:

NULL
  • All references to describe the role of the global variables available in the domain - about $ GLOBALS

Explanation

$ GLOBALS: a combination that contains an array of all global variables. The key variable is the name of the array.

example

<?php
function test() {
    $foo = "local variable";//函数内部变量

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
    echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";//函数外部变量
test();
?>

Output

$foo in global scope: Example content
$foo in current scope: local variable
  • If unset in the function () by a variable passed by reference, only the local variable is destroyed. The variable in the calling environment will keep calling unset () before the same value.

Examples

<?php
function foo(&$bar) {
    unset($bar);
    $bar = "blah";
    echo $bar;
    echo "<br/>";
}
 
$bar = 'something';
echo $bar;
echo "<br/>";
foo($bar);
echo $bar;
?>

The above example will output:

something
blah
something
  • If unset () a static variable in the function, then the static variable will be destroyed within the function. However, when this function is called again, this static variables will be restored to the last value before being destroyed.

Examples

<?php
function foo()
{
    static $bar;
    $bar++;
    echo "Before unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "after unset: $bar\n";
}
 
foo();
foo();
foo();
?>

The above example will output:

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23
Published 17 original articles · won praise 1 · views 894

Guess you like

Origin blog.csdn.net/weixin_43914604/article/details/97259693