php会话flash消息

问题描述 投票:2回答:3

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

我有控制器类

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

我也有Controller子类Home,其中函数由路径运行,如/ 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'));
    }
}

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

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

$this->message未定义为什么?

php session controller
3个回答
0
投票

在您提供的代码中,$message永远不会被定义为Controller类或其派生类Home的成员。如果要使用该成员变量,则必须将其声明为该类的成员,I.E。 public $message然后把它设置在执行的某个地方,大概是在你的Uri::redirectToAction函数中。


0
投票

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

From the php manuel

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

只需删除__destruct函数即可。


0
投票

我为这类项目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(); 
}

它将生成Bootstrap友好警报消息。

© www.soinside.com 2019 - 2024. All rights reserved.