Page 1 of 1
Best way to unload variables
Posted: Thu Mar 24, 2005 10:46 pm
by php_wiz_kid
I was just wanting to know which was is better to unload unwanted variables (such as $_SESSION variables). I'm currently using the unset() function, but I was wondering if setting the variable to null would be better practice. Thanks in advance.
Posted: Thu Mar 24, 2005 11:12 pm
by John Cartwright
Unset is fine, but it will completely unset the varialble, as in it won't exist anymore.
It would then trigger errors in parts of code like
You will now have un undefined error.
What I generally like to do is
$var = array();
Now $var has lost its value, but still exists.
Posted: Thu Mar 24, 2005 11:24 pm
by Burrito
I use unset(), but I always check if my vars exist with isset() and then put my var stuff in those blocks...guess it's a matter of personal preference...gonna try your way phenom
Burr
Posted: Thu Mar 24, 2005 11:27 pm
by John Cartwright
Burrito wrote:I use unset(), but I always check if my vars exist with isset() and then put my var stuff in those blocks...guess it's a matter of personal preference...gonna try your way phenom
Burr
You are correct, you should infact have it properly setup so if the var may not exist, you should be checking to see if it exists, and then check for your expected values.
Sometimes however, a blank value is what you require, sometimes no var..
all depends on the situatin and how you have it setup, I guess..
Posted: Thu Mar 24, 2005 11:31 pm
by php_wiz_kid
Here's some sample code
Code: Select all
if(isset($_SESSION['somevar'])) {
unset($_SESSION['somevar']);
}
What about that? This is actually what I'm doing.
Posted: Thu Mar 24, 2005 11:40 pm
by John Cartwright
Depends what you want to do with it? Completely erase the variable? or erase only its value..
This generally is not a problem with smaller applicatins, but is very important how you handle your variable in large scale applications.
Posted: Thu Mar 24, 2005 11:42 pm
by Burrito
well that works to unset your vars, but I was referring more to something like this.
Code: Select all
if(isset($_GETї'logout'])){
unset($_SESSIONї'loggedin']);
}
other stuff in other parts of the page to check if the loggedin var is set:
Code: Select all
if(isset($_SESSIONї'loggedin'])){
echo "e;hello "e;.$_SESSIONї'name'];
}else{
echo "e;you need to log in"e;;
}
that way you won't get errors if you try to call the $_SESSION['loggedin'] var if it's not set.
Burr
edit: oops forgot to end my php tag...