简体   繁体   中英

Notice: Trying to get property of non-object

I'm still following the login/register tutorial I have went over the videos a few times to see if maybe I made a typing mistake somewhere but I can't seem to find anything the error I'm getting is "Notice: Trying to get property of non-object"

I did look around it was suggested to try the below solution however it didn't work:

echo $user[0]->data()->username;

I know it has something to do with my data class, well I think it's my data class that's wrong.

index.php

  <?php
        require_once 'core/init.php';

    if(Session::exists('home')){
        echo '<p>' . Session::flash('home', 'You have been registered and can now log in!') . '</p>';
    }

    $user = new User();
    echo $user->data()->username;
    ?>


    <a href="login.php">Login</a>

User.php

 <?php
    class User{
        private $_db,
                $_data,
                $_sessionName;

        public function __construct($user = null){
            $this ->_db = DB::getInstance();

            $this->_sessionName = Config::get('session/session_name');

        if(!$user){
            if(Session::exists($this->_sessionName)){
                $user = Session::get($this->_sessionName);

            if($this->find($user)){
                $this->_isLoggedIn = true;
                    }else{
                        //logout 
                    }
                }
            } else{
                $this->find($user);
            }
        }


        public function create($fields = array()){
            if($this->_db->insert('users', $fields)){
                throw new Exception('There was a problem creating account');
            }
        }

        public function find($user = null){
            if($user){
                $field = (is_numeric($user)) ? 'id' : 'username';
                $data = $this->_db->get('users', array($field, '=', $user));

                if($data->count()) {
                    $this->_data = $data->first();
                    return true;
                }
            }
            return false;
        }
        public function login($username = null, $password = null){
                $user = $this->find($username);

            if($user){
                if($this->data()->password ===Hash::make($password, $this->data()->salt)){
                    Session::put($this->_sessionName, $this->data()->id);
                    return true;
                }
            }       
            return false;
        }

        public function data(){
            return $this->_data;
        }

    }

Login.php

<?php
require_once 'core/init.php';

if(Input::exists()){
    if(Token::check(Input::get('token'))){

        $validate = new Validate();
        $validation = $validate->check($_POST, array(
            'username' => array('required' => true),
            'password' => array('required' => true)
        ));

        if ($validation->passed()){
            //log user in
            $user = new User();
            $login = $user->login(Input::get('username'), Input::get('password'));

            if($login){
                echo 'Success';


            }else{
                echo'<p>Sorry invalid details</p>';
            }
        } else{
            foreach($validation->errors() as $error)
                echo $error, '<br />';
        }
    }
}

?>
<form action="" method="POST">
    <div class="field">
        <label for="username" id="username"> Username </label>
        <input type="text" name="username" id="username" autocomplete="off">
    </div>

    <div class="field">
        <label for="password" id="password"> Password </label>
        <input type="password" name="password" id="password" autocomplete="off">
    </div>
    <input type="hidden" name="token" value="<?php echo Token::generate();?>">
    <input type="submit" value="Login">
</form> 

<a href ="index.php">Home</a>

Session.php

<?php
class Session {
    public static function put($name, $value){
        return @$_SESSION[$name] = $value;
    }
    public static function get($name)
    {
        return self::exists($name) ? @$_SESSION[$name] : null;
    }
    public static function exists($name)
    {
        return @$_SESSION[$name] !== null;
    }
    public static function delete($name){
        if(self::exists($name)){
            unset($_SESSION[$name]);
        }
    }

    public static function flash($name, $string =''){
        if(self::exists($name)){
            $session = self::get($name);
            self::delete($name);
            return $session;
        } else {
            self::put($name, $string);
        }
    }
}

I'm assuming this is the offending code:

$user = new User();
echo $user->data()->username;

This code instantiates a User object, and we can see that the constructor expects the username (or possibly id?) to be given. If no username is given it looks like the find function simply returns false and hence the data array will be empty. This is why you get the error message.

Try calling the constructor with the current username, eg

$user = new User('test');

If it's possible for the index page to be loaded without a username, then you just need to add an additional check on the data object before you try to use it, eg

if (@$user->data())    
    echo $user->data()->username;
else
    echo "Not logged in";

我的init.php文件中的基本键入错误,我真的很讨厌自己...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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