How to access variables from a object in php?

2019-09-20 09:13发布

问题:

I'm following PHP Academy OOP Login/Register Tutorial currently in 16th part.

I used this code to create object in $data.

$data = $this->_db->get('users', array($field, '=', $user));

Then this code to add values from that object.

$this->_data = $data;

and trying to access the variables there by

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

$this->data()->password

The last code is throwing error. I tried to debug using this code

$vars = get_object_vars ($this->_data);
print_r($vars);

That is printing this line

Array ( [error] => [_requests] => Array ( [0] => stdClass Object ( [uid] => 16 [username] => admin [password] => 46651b6f1d743345d82d32da2cda7f891016ebe9f8b4416314b127e35b72fc30 [salt] => ²ê$ÓÕBF49ð®}€Æ¥A];ÛAc«íÊùÍ„s [name] => admin [joined] => 2015-03-17 22:53:52 [groups] => 1 ) ) ) 

What does this mean? How can I access those fields?

Here is the full code: DB.php

<?php
/**
 * Connect to database.
 *
 */
class DB{
    private static $_instance = null;
    private $_pdo, 
            $_query, 
            $_error = false,
            $_results,
            $_count = 0;

    private function __construct()
    {
        try
        {
        $this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';'.
                                'dbname='.Config::get('mysql/db'),
                                Config::get('mysql/username'),
                                Config::get('mysql/password')
            );
        }
        catch(PDOException $e)
        {
            die($e->getMessage());
        }
    }

    public static function getInstance()
    {
        if(!isset(self::$_instance))
        {
            self::$_instance = new DB();
        }
        return self::$_instance;
    }

    public function query($sql, $params = array())
    {
        $this->error = false;
        if($this->_query = $this->_pdo->prepare($sql))
        {   
            $x = 1;
            if(count($params))
            {
                foreach ($params as $param) 
                {
                    $this->_query->bindvalue($x, $param);
                    $x++;
                }
            }

            if($this->_query->execute())
            {
                $this->_requests    = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count       = $this->_query->rowCount();
            }
            else
            {
                $this->_error = true;
            }
        }

        return $this;
    }

    public function action($action, $table, $where = array())
    {
        if(count($where) === 3)
        {
            $operators  = array('=', '>', '<', '>=', '<=');

            $field      = $where[0];
            $operator   = $where[1];
            $value      = $where[2];

            if(in_array($operator, $operators))
            {
                $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
                if(!$this->query($sql, array($value))->error())
                {
                    return $this;
                }
            }
        }
        return false;
    }

    public function get($table, $where)
    {
        return $this->action('SELECT *', $table, $where);
    }

    public function delete($table, $where)
    {
        return $this->action('DELETE', $table, $where);
    }

    public function insert($table, $fields = array())
    {
        if(count($fields))
        {
            $keys   = array_keys($fields);
            $values = '';
            $x      = 1;

            foreach ($fields as $field) {
                $values .= '?';
                if($x < count($fields))
                {
                    $values .= ', ';
                }
                $x++;
            }

            // die($values);

            $sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";

            echo $sql;

            if(!$this->query($sql, $fields)->error())
            {
                return true;
            }
        }
        return false;
    }

    public function update($table, $id, $fields)
    {
        $set    = '';
        $x      = 1;

        foreach ($fields as $name => $value) {
            $set .= "{$name} = ?";
            if($x < count($fields))
            {
                $set .= ', ';
            }
            $x++;
        }

        $sql = "UPDATE {$table} SET {$set} WHERE uid = {$id}";

        if(!$this->query($sql, $fields)->error())
        {
            return true;
        }
        return false;
    }

    public function results()
    {
        return $this->_results;
    }

    public function first()
    {
        return $this->results()[0];
    }

    public function error()
    {
        return $this->_error;
    }

    public function count()
    {
        return $this->_count;
    }
}

user.php

<?php

class User{
    private $_db,
            $_data;

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

    public function create($fields = array())
    {
        if(!$this->_db->insert('users', $fields))
        {
            throw new Exception("Problem Creating User Account");

        }
    }

    public function find($user = null)
    {
        if($user)
        {
            $field  = (is_numeric($user)) ? 'uid' : 'username';

            $data = $this->_db->get('users', array($field, '=', $user));

            if($data->count())
            {
                $this->_data = $data;

                $vars = get_object_vars ($this->_data);
                print_r($vars);

                return true;
            }
        }
    }

    public function login($username = null, $password = null)
    {
        $user = $this->find($username);

        if($user)
        {
            if($this->data()->password === Hash::make($password, $this->_data->salt))
            {
                echo "ok";
            }
        }
        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 Validation();
            $validation = $validate->check($_POST, array(
                'username'  => array(
                    'required'  => true
                    ),
                'password'  => array(
                    'required'  => true
                    ),
            ));

            if($validation->passed())
            {
                $user   = new User();

                $login  = $user->login(Input::get('username'), Input::get('password'));
                if($login)
                {
                    echo "Success";
                }
                else{
                    echo "sorry! Failed";
                }
            }
            else{
                foreach ($validation->errors() as $error) {

                    echo $error, '<br />';
                }
            }
        }
    }
?>
<form action="" method="post">
    <div class="field">
        <label for="username">Username</label>
        <input type="text" name="username" id="username" autocomplete="off">
    </div>
    <div class="field">
        <label for="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="Log In">
</form>

回答1:

The variable returns array output. So you need to get values like $this->_data[0]->password, $this->_data[0]->username. Or when you store value to $this->_data, you can store the first child of the array.

instead of

$this->_data = $data;

You can use

$this->_data = $data->first();

So now you can get fields like $this->_data->username,$this->_data->password



标签: php oop