Jason Jason - 1 year ago 67
PHP Question

Is there a way to automatically unset a variable after accessing in php?

I am trying to display success or failure messages using session variables. I want them to be unset once the session variable once it is accessed. Is there some kind of PHP configuration where I can do it automatically with out writing any extra code?

I want something like this:

$_SESSION['message'] = 'print success';
echo $_SESSION['message'];
unset($_SESSION['message'])// I want this to be done automatically.

Could somebody help me with this?

Answer Source

You can write your own session handler and have a custom method for that. I strongly suggest Illuminate/Session, though, and use it's flash feature which keeps items in flash bag for the duration of one request only.

class Session {
   public function read($str){
      return isset($_SESSION[$str]) ? $this->deleteAndRet($str) : null;
   protected function deleteAndRet($str){
      $ret = $_SESSION[$str];
      return $ret;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download