【问题标题】:Echo a string in a class from a page in another page?从另一个页面中的页面回显一个类中的字符串?
【发布时间】:2015-04-05 17:00:07
【问题描述】:

我有两个页面 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>

【问题讨论】:

标签: php function echo inner-classes


【解决方案1】:

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

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

或者更好的是让它成为用户类的成员变量:

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

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多