如何在一个函数中存储值并在另一个函数中检索该值

时间:2012-11-03 13:09:33

标签: php function

我正在尝试在我的网站中实现像追随者功能的推特。我的插件中有这样的函数:

function current_profile_user_id() {
   return "current profile user id";
}
function button( $args = '' ) {
        $defaults = array(
            'leaderid'   => current_profile_user_id(),
            'followerid' => 'logged in user id'
        );
        return "HTML button";
    }

我可以通过函数参数从用户个人资料页面传递当前个人资料用户ID值的唯一方法。

假设$currentuser->ID返回当前个人资料页面的用户值,但此变量仅在个人资料页面中可用。

有谁能告诉我如何将该值传递给函数current_profile_user_id(),存储该值并返回html按钮?

请注意:我的许多其他功能也使用current_profile_user_id()返回的值。

1 个答案:

答案 0 :(得分:2)

您最好在会话中保存该值。函数可能依赖于全局范围,但不会在页面之间保存。

您可以执行类似

的操作
function currentProfile($profile = False)
{
    if ($profile)
        $_SESSION['curr_profile'] = $profile;
    else
        if (isset($_SESSION['curr_profile']))
            return $_SESSION['curr_profile'];
    return $profile;
}

function current_profile_user_id()
{
    return currentProfile()->ID;
}

然后,请尽快将个人资料保存在会话

currentProfile($currentuser);

......应该工作。这样,您可以根据需要更改curr_profile的持久性,而无需重新访问所有代码。

关于可能相关的说明

(不清楚你要做什么以及如何做,我希望这可能会变得有用)

因此,您有一个用户列表,并希望为每个用户显示“关注”模板。从某种数据库中检索用户列表,因此您将拥有类似

的内容
while($user = $st->fetch(PDO::FETCH_ASSOC))
{
    // Populate the template

    // Append template to display code
}

在该模板中,您将拥有以下内容:

<a href="follow.php?id={$user['id']}">Follow {$user['name']}</a>

或者可能是一个AJAX调用,将该用户添加到已记录用户的后续列表中而不刷新页面。无论如何,将会调用服务器页面,该页面将收到会话cookie 和用户选择的ID。

因此,该页面必须记下新的关注/取消关注,并且它将拥有所需的一切:

  1. $_REQUEST['id']
  2. 中要关注的用户的ID
  3. 关注者的所有数据,在$_SESSION
  4. 然后,它可以执行例如

    之类的查询
     INSERT IGNORE INTO followers (follower, followee) VALUES ($id1, $id2);
    

    坚持信息。