Pawan Choudhary
Pawan Choudhary

Reputation: 1083

php function to unset variables passed by reference

currently i'm using this php function :

function if_exist(&$argument, $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.

Upvotes: 16

Views: 9420

Answers (4)

SIDU
SIDU

Reputation: 2278

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]

Upvotes: 0

DonSeba
DonSeba

Reputation: 2119

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();
?>

Upvotes: 1

George Cummins
George Cummins

Reputation: 28936

$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; 

Upvotes: 2

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;

Upvotes: 22

Related Questions