C#TempData等价于php [英] c# TempData equivalent in php
问题描述
我知道我可以手动显式设置和取消设置会话,但是我认为这值得一问.在c#中,有一个名为TempData的字典,该字典存储数据直到第一个请求.换句话说,调用TempData时,它将自动取消设置.为了更好地理解,这里是一个示例:
I know I can explicitly set and unset a Session manually but I believe this is worth to ask. In c#, there is a dictionary called TempData which stores data until the first request. In other words, when TempData is called, it is automatically unset. For a better understanding here is an example:
Controller1.cs:
Controller1.cs:
TempData["data"] = "This is a stored data";
Model1.cs:
Model1.cs:
string dst1 = TempData["data"]; // This is a stored data
string dst2 = TempData["data"]; // This string will be empty, if an exception is not raised (I can't remember well if an exception is raised)
因此,基本上,这就像一个只能使用1次的会话.同样,我知道我可以在php中显式设置和取消设置,但是php是否具有像这样的功能?
So basically, this is just something like a session for 1 use only. Again, I know that I can set and unset explicitly in php, but still, does php has a function like this one?
推荐答案
使用会话来启用TempData.这是一个简单的PHP实现:
As the others have pointed out, uses sessions to enable TempData. Here is a simple PHP implementation:
class TempData {
public static function get($offset) {
$value = $_SESSION[$offset];
unset($_SESSION[$offset]);
return $value;
}
public static function set($offset, $value) {
$_SESSION[$offset] = $value;
}
}
测试:
TempData::set("hello", "world");
var_dump($_SESSION); // array(1) { ["hello"]=> string(5) "world" }
TempData::get("hello"); // => world
var_dump($_SESSION); // array(0) { }
不幸的是,我们不能使用静态类来实现ArrayAccess.
Unfortunately, we can not implement ArrayAccess with a static class.
这篇关于C#TempData等价于php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!