开发者

php function to unset variables passed by reference

currently i'm using this php function :

function if_exist(&$ar开发者_Go百科gument, $default = '')
{
    if (isset ($argument))
    {
        echo $argument;
    }
    else
    {
        echo $default;
    }
}

i want this function to unset the variables $argument(passed by reference) and $default just after echoing their value, how can i do this? Thanks in advance.


According to the manual for unset:

If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

I assume this is the issue you're encountering. So, my suggestion is to simply set $argument to NULL. Which, according to the NULL docs will "remove the variable and unset its value.".

For example: $argument = NULL;


$default is passed by value, so it cannot be unset (except in the local scope).

As you undoubtedly discovered, unset() simply unsets the reference to $argument. You can (sort of) unset $argument like this:

$argument = null; 


the only way to do this with a function is using globals.

//To unset() a global variable inside of a function,
// then use the $GLOBALS array to do so: 

<?php
function foo() 
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>


If var is not array, and passed by reference, unset is actually unset the pointer, so it will not affect the original.

However if the var is array, you can unset its keys. eg:

$arr = [
    'a' => 1, 
    'b' => ['c' => 3],
];

function del($key, &$arr) {
    $key = explode('.', $key);
    $end = array_pop($key);
    foreach ($key as $k) {
        if (is_array($arr[$k]) {
            $arr = &$arr[$k];
        } else {
            return; // Error - invalid key -- doing nothing
        }
    }
    unset($arr[$end]);
}

del('b.c', $arr); // $arr = ['a' => 1, 'b' => []]
del('b',   $arr); // $arr = ['a' => 1]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜