开发者

flash_set, flash_get in PHP?

开发者 https://www.devze.com 2022-12-20 15:06 出处:网络
so i got told in this question: PHP/Javascript passing message to another page to use flash_set and flas开发者_C百科h_get, concept called \"Rails flash\".. Now can you use them in php those function?

so i got told in this question: PHP/Javascript passing message to another page

to use flash_set and flas开发者_C百科h_get, concept called "Rails flash".. Now can you use them in php those function? I can really find them in php library site, so im not sure..


You can store the messages you want to flash on the next page request in the $_SESSION. I don't know exactly how the methods work in rails but hopefully these two functions can be of use:

function flash_get()
{
    // If there are any messages in the queue
    if(isset($_SESSION['flashMessages']))
    {
        // Fetch the message queue
        $messages = $_SESSION['flashMessages'];

        // Empty out the message queue
        unset($_SESSION['flashMessages']);

        return $messages;
    }

    // No messages so just return an empty array
    return array();
}

function flash_set($message)
{
    // If the queue is currently empty we need to create an array
    if(!isset($_SESSION['flashMessages'])) {
        $_SESSION['flashMessages'] = array();
    }

    // Fetch the current list of messages and append the new one to the end
    $messages = $_SESSION['flashMessages'];
    $messages[] = $message;

    // Store the message queue back in the session
    $_SESSION['flashMessages'] = $messages;
}

Just call flash_set() with the message you want to store and flash_get() will give you that array back and flush the queue on a later page request.

You'll have to make sure as well that you call session_start() with every page request for these methods to work.


There's no a built-in function in PHP to achieve this, but if you use some frameworks as CakePHP (which is inspired on rails), you'll find it quite simple:

// In the controller
$this->Session->setFlash('message to flash');

// In the view
$session->flash();

I bet some other frameworks have this covered.

0

精彩评论

暂无评论...
验证码 换一张
取 消