问题
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?
回答1:
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, I.E. public $message and then set it somewhere in execution, presumably in your Uri::redirectToAction function.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/18748240/php-session-flash-message