Function to destroy a variable

0

I am trying to make a function that combines the assignment of variables with their subsequent destruction. I had in mind to do something like this:

function setunset(&$sesion){
    $salida = $sesion;
    unset($sesion);
    return $salida;
}

$_SESSION['uno'] = '1';
$uno = setunset($_SESSION['uno']);

echo $uno; // Devuelve 1
echo $_SESSION['uno'] // Devuelve "undefined index"

I am seeing that this as it would not be possible because the destruction of the variable remains within the scope of the function and therefore, $_SESSION['uno'] would still exist. ( PHP Documentation )

Is there any other way to do it? Or will I have to settle for making it classic (first assign and then destroy)?

    
asked by José González 17.07.2018 в 10:41
source

1 answer

0

Pass the parameter and do the unset of the session of that parameter, and not of its value.

I'll give you an example in parallel with yours, the second bis function does the unset of the session for the parameter you pass:

function setunset(&$sesion){
    $salida = $sesion;
    unset($sesion);
    return $salida;
}
function setunsetbis($sesion){
    $salida = $_SESSION[$sesion];
    unset($_SESSION[$sesion]);
    return $salida;
}

$_SESSION['uno'] = '1';
echo $_SESSION['uno']; echo " a<br>"; // Devuelve 1
$uno = setunset($_SESSION['uno']);
echo $uno;  echo " b<br>"; // Devuelve 1
echo $_SESSION['uno'];  echo " c<br>"; // Devuelve 1
$unobis = setunsetbis('uno');
echo $unobis;  echo " d<br>"; // Devuelve 1
echo $_SESSION['uno'];  echo " e<br>"; // No está

Result

1 a
1 b
1 c
1 d
e

If you do a var_dump($_SESSION) you will see that% is not $_SESSION['uno'] .

    
answered by 17.07.2018 в 11:42