【发布时间】:2010-01-17 18:18:16
【问题描述】:
在 PHP 中,我知道很多人会使用一个类来设置和获取会话变量,我现在在很多类中都这样做,但我需要知道我是否做错了。
例如,假设我有一个需要使用它的类
$session->get('user_id')
哪个得到这个值
$_SESSION['user_id']
现在在这个类中,如果我有 15 个方法并且在每个方法中我需要多次访问这个值,目前我在一个类中调用 $session->get('user_id') 20 次,如果需要 20 次,我是否应该将每个班级的 1 次设置为该班级的局部变量,然后访问它?我不确定它是否有任何区别,我的理论是我现在这样做的方式是可以避免 20 个额外的函数调用?
如果我的理论是正确的,那么将这些值存储在类中的最佳方法是什么?像私有或公共或受保护的变量?
谢谢,对于任何混淆,类和对象需要我一段时间来学习。
还要注意 $session->get('user_id') 只是我需要做同样事情的许多不同变量中的一个。
更新
在阅读了 Chacha102 的关于使用 array() 的帖子...这是我尝试过的,这看起来是一个好方法还是仍然可以改进很多?
类文件
<?PHP
class User
{
// Load user details into an Array
public function load_user()
{
$this->user_id = $this->session->get('user_id');
//if user ID is already set, then Load the cached urser data
if(isset($this->user_id) && $this->user_id != ''){
// set user data to an array
$this->user['user_id'] = $this->user_id;
$this->user['user_name'] = $this->session->get('user_name');
$this->user['pic_small'] = $this->session->get('pic_small');
$this->user['sex'] = $this->session->get('sex');
$this->user['user_role'] = $this->session->get('user_role');
$this->user['location_lat'] = $this->session->get('location_lat');
$this->user['location_long'] = $this->session->get('location_long');
$this->user['new_user'] = $this->session->get('new_user');
return $this->user;
}
}
}
?>
主页文件
<?PHP
require 'user.class.php';
$user = new User;
// if a user_id is set into a session variable then we return an array of other user related data
$user->account = $user->load_user();
// would show the user's ID from our array
echo $user->account['user_id'];
?>
【问题讨论】: