php函数没有返回类对象

时间:2013-05-10 01:19:14

标签: php oop class object

我有一个DB类,我已经创建了几个函数来返回各种值。其中一个函数返回(或应该)一个“用户”类对象,该对象表示应用程序的登录用户。

class user {
   public $guid = '';
   public $fname = '';
   public $lname = '';

   public function __construct() {}

   public function print_option() {
         return "<option value='$this->guid'>$this->name</option>";
   }
}

在DB类中,我有以下两个函数:

public function get_user($uid) {
    $sql = '';
    $usr = new user();
    $sql = "SELECT guid, fname, lname FROM ms.users WHERE guid=?";

    if($sth = $this->conn->prepare($sql)) {
        $sth->bind_param('s', $uid);
        if($sth->execute()) {
            $sth->bind_result($usr->guid, $usr->fname, $usr->lname);
            $sth->fetch();
            print_r($usr);  // PRINTS OUT CORRECTLY
            return $usr;
        }
        else {return null;}
    }
    else {return null;}
}

public function get_practice_user_list($pguid) {
    $ret = '';
    $sql = "SELECT user_guid FROM ms.perm WHERE p_guid=?";
    if($sth = $this->conn->prepare($sql)) {
        $sth->bind_param('s', $pguid);
        if($sth->execute()) {
            $usr = new user();
            $guid = '';

            $sth->bind_result($guid);
            while($sth->fetch()) {
                print_r($guid);  // PRINTS GUID correctly
                $usr = $this->get_user($guid);
                print_r($usr);   // PRINTS NOTHING object is null so prints "error" two lines later.
                if($usr != null) $ret .= $usr->print_option();
                else print "error";
            }

            return $ret;
        }
        else {return null;}
    }
    else {return null;}
}

我只是不明白为什么“user”对象在这个实例中没有返回。其他调用get_user函数的工作正常,并返回与该用户相关的用户类对象。

TIA

2 个答案:

答案 0 :(得分:0)

我猜你guid可能是一个整数所以

    $sth->bind_param('s', $uid);

bind_param的第一个参数应该是'我'不是';

http://www.php.net/manual/en/mysqli-stmt.bind-param.php

答案 1 :(得分:0)

问题在于查询。由于代码只是循环遍历一个查询(get_practice_user_list),然后调用get_user函数并尝试第二个查询MySQL返回时出现out of sync消息错误。当我查看它时,我能够通过在第一个查询上执行fetch_all然后循环遍历该数组来获取用户来修复它。