如何从php中的对象访问变量?

时间:2015-03-19 06:16:48

标签: php oop

我正在关注16th part中的PHP Academy OOP登录/注册教程。

我使用此代码在$ data中创建对象。

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

然后使用此代码添加该对象的值。

$this->_data = $data;

并尝试通过

访问那里的变量
public function data(){
    return $this->_data;
}

$this->data()->password

最后一个代码是抛出错误。我尝试使用此代码进行调试

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

即打印此行

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 ) ) ) 

这是什么意思?我如何访问这些字段?

以下是完整代码: 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 个答案:

答案 0 :(得分:0)

该变量返回数组输出。因此,您需要获取 $ this-&gt; _data [0] - &gt;密码,$ this-&gt; _data [0] - &gt;用户名等值。或者当您将值存储到$ this-&gt; _data时,您可以存储数组的第一个子项。

而不是

$this->_data = $data;

您可以使用

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

现在您可以获得$ this-&gt; _data-&gt; username,$ this-&gt; _data-&gt; password

等字段