简体   繁体   中英

Weird unset() issue with session variable

I have a function which gets a session variable by a key and then reassigns it to a variable. I unset the session variable and return the variable I set. For some reason it is returning ''. If I remove the unset it works.

This returns null

if(isset($_SESSION[$key])) {
            $session_variable = $_SESSION[$key];
            var_dump($session_variable);
            unset($_SESSION[$key]);
            var_dump($session_variable);
            return $session_variable;
        }
    return '';

This returns the correct output when unset is omitted

if(isset($_SESSION[$key])) {
            $session_variable = $_SESSION[$key];
            var_dump($session_variable);
//          unset($_SESSION[$key]);
            var_dump($session_variable);
            return $session_variable;
        }
        return '';

I don't understand why unset is removing the variable $session_variable.

EDIT

The session variable previous is being set like this

$_SESSION['action'] = ['message' => 'bla', 'status' => 'success'];

The function is being called like this

(new Request)->getFlashedSessionVar('action'); //For testing

It depends on what the $_SESSION[$key] really is. According to PHP documentation: An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword.

This means you could just assign by reference and therefore endup unsetting the same object.

Please read here: PHP Assignment Operators

I just tested your code in raw PHP. Its working fine for me

Code

<?php 
    session_start();
    $key = 'action';
    $_SESSION[$key] = [ 1 ,2] ;
    if(isset($_SESSION[$key])) {
            $session_variable = $_SESSION[$key];
            var_dump($session_variable);
            unset($_SESSION[$key]);
            var_dump($session_variable);
            return $session_variable;
        }
    return '';
?>

Output

array(2) { [0]=> int(1) [1]=> int(2) } array(2) { [0]=> int(1) [1]=> int(2) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM