简体   繁体   中英

php session flash message

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?

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.

In the code you provided $message is never defined as a member of the Controller class or its derived class Home . If you want to use that member variable you have to declare it as a member of the class, IE public $message and then set it somewhere in execution, presumably in your Uri::redirectToAction function.

I wrote a library just for this type of projects https://github.com/tamtamchik/simple-flash .

Once you have it installed you can do this.

In your redirectToAction :

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

And in index :

public function index()
{
    echo flash()->display(); 
}

It'll generate Bootstrap friendly alert messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM