Jason Jason - 4 months ago 27
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?


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;