从另一个页面中的页面回显类中的字符串?

时间:2015-04-05 17:00:07

标签: php function echo inner-classes

我有两个页面login.php和user.php(其中消息=错误的组合,我要回应他)我试图在login.php中显示一条消息,该消息来自user.php,它基于错误的组合的电子邮件和密码请问如何在我的login.php中显示消息,下面是我的代码

下面的user.php页面

class Users {       
    function login($find='') {
        if(($rows["email"] == $email)&&($rows["password"] == $password)){
            $_SESSION['email'] = $email;
            $_SESSION['password'] = $password;

            if (isset($_POST['remember'])){
                setcookie("cookname", $_SESSION['email'], time()+60*60*24*100, "/");
                setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
            }

            $_SESSION['user_id'] = $user_id;
            return true;
        }
        else {
            $message =  'Wrong Combination';
            return false;
        }
    }
}

下面的login.php页面

<?php
    include_once("user.php");
    if (isset($_POST['submit'])) 
    {   
        $find = $user->login($_POST);
        if ($find)
        {
            header ("location: panel.php");
            exit;
        }
    }
?>

<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
    <form name="form1" method="post" action="">
        <!-- I want to echo it here I echo the variable message but did not work -->
        <?php echo "$message";?>
        input id="email" />
        <input id="password" />
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的$message变量在Users类的登录功能中具有本地范围,因此您无法在该函数之外的当前范围内使用它。您可以将其保存到会话中,即:

$_SESSION['message'] = 'Wrong Combination';

或者更好的是使它成为Users类的成员变量:

class Users {    
  protected message = '';

  public function getMessage(){ return $this->message; }

  function login($find='') {
    if(($rows["email"] == $email)&&($rows["password"] == $password)){
      $_SESSION['email'] = $email;
      $_SESSION['password'] = $password;
      if(isset($_POST['remember'])){
        setcookie("cookname", $_SESSION['email'], time()+60*60*24*100, "/");
        setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
      }

      $_SESSION['user_id'] = $user_id;
      return true;
    }else{
      $this->message =  'Wrong Combination';
      return false;
    }
  }
}

然后在要显示消息的登录表单中:

<?php 
  $message = $user->getMessage();
  if (!empty($message)) 
    echo $message;
?>

顺便说一句,我不知道你在哪里实例化Users类。我假设您在login.php中使用它时未显示的代码中创建$user