Facebook PHP API在<div> </div>中使用时给出不一致的结果

时间:2014-01-06 02:30:52

标签: php facebook facebook-login

我正在使用Facebook PHP SDK和Facebook JS SDK(使用JS SDK来处理登录,就像这里讨论的那样:https://developers.facebook.com/blog/post/534/)。

我有一个自定义按钮,我已创建并附加到FB.login()函数。我的目标是让该按钮内的文字说“如果用户没有登录则使用Facebook登录”,如果用户登录,则按钮内的文本显示用户姓名。

问题在于,当我尝试引用具有登录用户信息的$ user_profile变量时,当我在按钮外部使用它时,它会起作用,但是当在按钮内部使用变量时,该变量未设置(以下代码)。可能导致这种情况的原因是什么?

<?php 

// Get the contents of static-head.html to open the HTML doc:
readfile("static-head.html");

// Include the Facebook PHP SDK so that we can have people login
require_once('fb/facebook.php');

$config = array(
  'appId' => 'MY_APP_ID',
  'secret' => 'MY_APP_SECRET',
  'allowSignedRequest' => false 
);

$facebook = new Facebook($config);
$user_id = $facebook->getUser();

// Get Facebook Login information
if($user_id) {
  // We have a user ID, so probably a logged in user.
  // If not, we'll get an exception, which we handle below.
  try {
    $user_profile = $facebook->api('/me','GET');
    // If this doesn't throw an error, we now we have a $user_profile that we can use
  } catch(FacebookApiException $e) {
    // If the user is logged out, you can have a user ID even though the access token is invalid.
    // In this case, we'll get an exception, so we'll just wait for the user to log in.
    error_log($e->getType());
    error_log($e->getMessage());
    // Set the $user_id to NULL so that there's no confusion elsewhere in the app.
    $user_id = NULL;
  }   
} else {
    // Let the user log in through the JavaScript SDK
}

  // Just to prove that $user_profile is being recognized:
  // ***This works! It returns "Chris"
  echo $user_profile['first_name'];

  // Function to set the text inside the LogIn/LogOut button:
  // ***This doesn't work! It returns "Log in with Facebook"
  function getLogInLogOutText(){
        if(isset($user_profile)){
            return $user_profile['first_name'];
        } else{
            return 'Log in with Facebook';
        }
    }
?>  
<div id="userLogInLogOut" class="uiControlsDivs">
    <button id="userLogInLogOutButton"><?php echo getLogInLogOutText(); ?></button>
</div>

我完全不知道这是怎么回事。在一行中,代码工作并返回Facebook用户的名称。然后,几行后,它不起作用!发生了什么事?!

感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:0)

尝试将变量解析为函数,所以说制作函数:

function getLogInOutText() { ...

进入

function getLogInOutText($user_profile) { ...

并与之打电话,即:

<?php echo getLogInOutText($user_profile); ?>

不确定它会起作用,但值得一试。否则尝试将其变为全局变量:

PHP reference for variables scope - http://www.php.net/manual/en/language.variables.scope.php

相关问题