Reputation: 2716
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
Upvotes: 0
Views: 42
Reputation: 324
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) }
Upvotes: 1
Reputation: 432
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
Upvotes: 1