有没有一种快速的方法将mysql对象结果分配给自定义类?

时间:2014-02-10 13:40:52

标签: php mysql

我正在创建很多对象,并且我经常遇到我经常将每个对象列逐个分配给每个内部对象变量。

如果有更快的方法来执行以下操作,我的创造力是什么?

public function load(){
    $result = $this->coredb->query("SELECT * FROM " . CORE_TBL_ORDER_LINE . " WHERE id=" . $this->id . " LIMIT 1");
    if($result !== false && $result->num_rows == 1){
        $obj = $result->fetch_object();

        // Can the following be done in a faster way? (Names do always match)
        $this->ISBN = $obj->ISBN;
        $this->type = $obj->type;
        $this->status = $obj->status;
        $this->updated = $obj->updated;
        $this->blocked = $obj->blocked;
        $this->created = $obj->created;
    }
    else
        $this->id = 0;
}

2 个答案:

答案 0 :(得分:0)

是的,你可以这样做:

public $row;

public function load(){
    $result = $this->coredb->query("SELECT * FROM " . CORE_TBL_ORDER_LINE . " WHERE id=" . $this->id . " LIMIT 1");
    if($result !== false && $result->num_rows == 1){

        $this->row = $result->fetch_object();

    }
    else
        $this->id = 0;
    }

答案 1 :(得分:0)

PDO允许您比MySQLi做得更好,并使您的代码可移植。您可以使用fetch方法设置PDO::FETCH_INTO标志,如PHP文档中所述:

/* or create an instance yourself and use it */
$user= new user();
$sth->setFetchMode( PDO::FETCH_INTO, $user);
$sth->execute();
$user= $sth->fetch( PDO::FETCH_INTO );
$sth->closeCursor();
print ($user->id);

PHP文档链接:http://us2.php.net/manual/en/pdostatement.fetch.php