php session flash message

10,436

It's because of your __destruct. When the execution is finished, __destruct function is called and it unset your $_SESSION['FLASH'] therefore, it is no longer accessible in your script.

From the php manuel:

The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

Just remove your __destruct function.

Share:
10,436
Gia Nebieridze
Author by

Gia Nebieridze

Updated on June 04, 2022

Comments

  • Gia Nebieridze
    Gia Nebieridze almost 2 years

    i'm tryning to create session flash message after redirection.

    i have Controller class

    class Controller
    {
        function __construct()
        {
        if(!empty($_SESSION['FLASH']))
            foreach($_SESSION['FLASH'] as $key => $val)
            $this->$key = $val;
        }
        function __destruct()
        {
            $_SESSION['FLASH']=null;
        }
    }
    

    also i have Controller child class Home, where functions are run by route, like /Home/Index => public function index()

    class Home extends Controller
    {
        function __construct()
        {
            parent::__construct();
        }
    
        public function index()
        {
            //where i want to display $this->message only once
            echo $this->message; // but $this->message is undefinded why? 
        }
        public function Post_register(){
            //after post form data
            // validation 
    
            // this function redirect to /Home/Index  above function index();
            Uri::redirectToAction("Home","Index",array('message' => 'some message'));
        }
    }
    

    and uri class function where i redirecting user.

    public static function redirectToAction($controller,$method,$arr)
    {
        $_SESSION['FLASH'] = $arr;
        header("Location:/".$controller.'/'.$method);
    }
    

    but $this->message is undefinded why?

  • Gia Nebieridze
    Gia Nebieridze over 10 years
    yes defined by this code if(!empty($_SESSION['FLASH'])) foreach($_SESSION['FLASH'] as $key => $val) $this->$key = $val; } if i remove destruct its working, but i want to display this message only once, then remove session
  • Bad Wolf
    Bad Wolf over 10 years
    @GiaNebieridze Then why don't you just unset() the session variables in the foreach loop in your constructor once your reset set the class member instead of using a destructor?
  • Gia Nebieridze
    Gia Nebieridze over 10 years
    oh thanks @Nico, it's working now :) i was thinking remove session in destructor but it was wrong. if(!empty($_SESSION['FLASH'])) foreach($_SESSION['FLASH'] as $key => $val) $this->$key = $val; unset($_SESSION['FLASH']); this working now :)