如何从php中的对象访问变量? [英] How to access variables from a object in php?

查看:42
本文介绍了如何从php中的对象访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 PHP Academy OOP 登录/注册教程,目前位于 第 16 部分.

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

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

然后此代码从该对象添加值.

$this->_data = $data;

并尝试通过

访问那里的变量

公共函数数据(){返回 $this->_data;}$this->data()->password

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

$vars = get_object_vars ($this->_data);打印_r($vars);

即打印这一行

Array ( [error] => [_requests] => Array ( [0] => stdClass Object ( [uid] => 16 [username] => admin [password] =>; 46651b6f1d743345d82d32da2cda7f891016ebe9f8b4416314b127e35b72fc30 [盐] => [²ê?$Ó ÕBF49„ð®}ÕBF49„ð®}ÕBF49„ð®}ÍÍÍÍ®}€Æjoin «25:>Í=5>-admin =>-admin =>25:25>2016ebe9f8b4416314b127e35b72fc30组] => 1 ) ) )

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

完整代码如下:数据库.php

_pdo = new PDO('mysql:host='.Config::get('mysql/host').';'.'dbname='.Config::get('mysql/db'),Config::get('mysql/用户名'),配置::get('mysql/密码'));}catch(PDOException $e){死($e->getMessage());}}公共静态函数 getInstance(){if(!isset(self::$_instance)){self::$_instance = new DB();}返回 self::$_instance;}公共函数查询($sql, $params = array()){$this->error = false;if($this->_query = $this->_pdo->prepare($sql)){$x = 1;如果(计数($params)){foreach ($params 作为 $param){$this->_query->bindvalue($x, $param);$x++;}}if($this->_query->execute()){$this->_requests = $this->_query->fetchAll(PDO::FETCH_OBJ);$this->_count = $this->_query->rowCount();}别的{$this->_error = true;}}返回 $this;}公共函数动作($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()){返回 $this;}}}返回假;}公共函数 get($table, $where){return $this->action('SELECT *', $table, $where);}公共函数删除($table,$where){返回 $this->action('DELETE', $table, $where);}公共函数插入($table,$fields = array()){如果(计数($ 字段)){$keys = array_keys($fields);$values = '';$x = 1;foreach ($fields 作为 $field) {$values .= '?';if($x < count($fields)){$values .= ', ';}$x++;}//死($values);$sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";回声 $sql;if(!$this->query($sql, $fields)->error()){返回真;}}返回假;}公共函数更新($table,$id,$fields){$set = '';$x = 1;foreach ($fields as $name => $value) {$set .= "{$name} = ?";if($x < count($fields)){$set .= ', ';}$x++;}$sql = "更新 {$table} SET {$set} WHERE uid = {$id}";if(!$this->query($sql, $fields)->error()){返回真;}返回假;}公共函数结果(){返回 $this->_results;}公共函数 first(){返回 $this->results()[0];}公共函数错误(){返回 $this->_error;}公共函数计数(){返回 $this->_count;}}

user.php

_db = DB::getInstance();}公共函数创建($fields = array()){if(!$this->_db->insert('users', $fields)){throw new Exception("创建用户账户的问题");}}公共函数查找($user = null){如果($用户){$field = (is_numeric($user)) ?'uid' : '用户名';$data = $this->_db->get('users', array($field, '=', $user));if($data->count()){$this->_data = $data;$vars = get_object_vars ($this->_data);打印_r($vars);返回真;}}}公共函数登录($username = null, $password = null){$user = $this->find($username);如果($用户){if($this->data()->password === Hash::make($password, $this->_data->salt)){回声好";}}返回假;}公共函数数据(){返回 $this->_data;}}

登录.php

 check($_POST, array('用户名' =>大批('必需' =>真的),'密码' =>大批('必需' =>真的),));if($validation->passed()){$user = 新用户();$login = $user->login(Input::get('username'), Input::get('password'));如果($登录){echo "成功";}别的{echo "对不起!失败";}}别的{foreach ($validation->errors() as $error) {echo $error, '<br/>';}}}}?><form action="" method="post"><div class="field"><label for="username">用户名</label><input type="text" name="username" id="username" autocomplete="off">

<div class="field"><label for="password">密码</label><input type="password" name="password" id="password" autocomplete="off">

<input type="hidden" name="token" value="<?php echo Token::generate(); ?>"><input type="submit" value="登录"></表单>

解决方案

变量返回数组输出.因此,您需要获取诸如 $this->_data[0]->password、$this->_data[0]->username 之类的值.或者当你存值到$this->_data时,你可以存数组的第一个子元素.

代替

$this->_data = $data;

你可以使用

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

所以现在你可以得到 $this->_data->username,$this->_data->password 之类的字段

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>

解决方案

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中的对象访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆