PHP 会话闪烁消息


php session flash message

我正在尝试在重定向后创建会话闪存消息。

我有控制器类

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

我也有控制器子类 Home,其中函数按路由运行,例如/Home/Index => 公共函数 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'));
    }
}

和 uri 类函数,我在其中重定向用户。

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

$this->message找不到为什么?

这是因为你的__destruct。执行完成后,将调用__destruct函数并取消设置 $_SESSION['FLASH'],因此,脚本中无法再访问它。

来自 php manuel:

析构函数方法将在没有对特定对象的其他引用时立即调用,或者在关闭序列期间以任何顺序调用。

只需删除您的__destruct功能即可。

在您

提供的代码中,$message从未定义为Controller类或其派生类Home的成员。如果你想使用该成员变量,你必须将其声明为类的成员,即 public $message,然后将其设置在执行中的某个位置,大概是在Uri::redirectToAction函数中。

我专门为这种类型的项目编写了一个库 https://github.com/tamtamchik/simple-flash。

安装后,您可以执行此操作。

在您的redirectToAction

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

并在index

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

它将生成引导友好的警报消息。