gpt4 book ai didi

php - 创建自己的 $_SESSION 类变量?

转载 作者:搜寻专家 更新时间:2023-10-31 21:36:44 25 4
gpt4 key购买 nike

这是我有点挑剔,但我真的很喜欢 $_SESSION 工作的轻松。所以我想知道是否有办法让我在数据库中的行像那样工作。我很容易做一个超全局的,所以例如 $_DATA['address'] 会返回保存在当前登录用户数据库中的地址。明显的问题是当我写$_DATA['whatever'] 它会自动将其写入数据库。这在我习惯的 C# 中很容易,但在 PHP 中似乎没有正常的获取/设置功能。我有什么办法可以完成我希望做的事情吗?

最佳答案

你可以创建一个类并给它一些静态辅助函数

例如:

class CurrentUser {

protected static $currentUser;
protected static function getCurrentUser(){
if (!static::$currentUser){
// get the current user from db and assign it to the currentUser Property
}
return static::$currentUser;
}
public static function get($property){
return isset(static::getCurrentUser()->$property)?static::$currentUser->$property:null;
}

public static function set($property, $value){
// make sure we have the current user
$user = static::getCurrentUser();
if ($user){
$user->$property = $value;
// save the user to the database.
}
}
}

要使用 then you would just say

echo CurrentUser::get("address");

echo CurrentUser::set("address", "123 anystreet, anytown US 12345");

关于php - 创建自己的 $_SESSION 类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17508385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com