简体   繁体   English

无法从 PHP 中的另一个文件获取 object 属性

[英]Cannot get object property from another file in PHP

I want to make a query to MySQL and if the query is done but if there is no result, I want to set "login_status" object property to false instead of NULL.我想查询 MySQL,如果查询完成但没有结果,我想将“login_status”object 属性设置为 false 而不是 NULL。

I have all files connected in one main file "load.php" so there is no problems with including files.我将所有文件连接到一个主文件“load.php”中,因此包含文件没有问题。

My query is defined in User.php file which containes User class with method login().我的查询在 User.php 文件中定义,该文件包含使用方法 login() 的用户 class。

Another file is login.view.php which is html template for login functionality, but I receive message that variable $user (isntance of User) is not defined and that property login_status isn't also defined.另一个文件是 login.view.php,它是用于登录功能的 html 模板,但我收到消息说变量 $user(用户的实例)未定义并且属性 login_status 也未定义。

Here's the code from User.php:这是来自 User.php 的代码:

class User extends Query {
    public $login_status;
    
    public function login(){
        $email = $_POST['login_email'];
        $pass = $_POST['login_pass'];
    
        $sql = "SELECT * 
                FROM tqyr_users 
                WHERE user_email = ? 
                AND user_pass = ?;";
        $query = $this->db->prepare($sql);
        $query->execute([$email, $pass]);
        $is_user = $query->fetch(PDO::FETCH_OBJ);
    
        if(is_object($is_user)){
            $_SESSION['logged'] = $is_user;
            header('Location: index.php');
        } else {
            $this->login_status = false;
            header('Location: login.php');
        }
    }.........

And here's the code from login.view.php:这是来自 login.view.php 的代码:

    <?php if($user->login_status == false): ?>
    <p class="px-4 py-4 bg-danger text-white text-start mb-4 login-alert">Wrong email or password, please try again.</p>
 

     <?php endif; ?>

Once again, I have all files connected and I have defined $user instance再一次,我连接了所有文件并且定义了 $user 实例

If 'else' is executed, it will force a new connection and consequently you will lose the variable state.如果执行“else”,它将强制建立新连接,因此您将丢失变量 state。

I suggest you change the responsibility of $_SESSION and header of this class.建议你把这个class的$_SESSION和header的responsibility改一下。

You can return true or false in login function.您可以在登录 function 中返回 true 或 false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM