【问题标题】:php function not returning class objectphp函数不返回类对象
【发布时间】:2013-05-10 01:19:14
【问题描述】:

我有一个 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 类中,我有以下 2 个功能:

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;}
}

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

TIA

【问题讨论】:

  • 你调用的是哪个函数,它到底返回了什么?
  • 我从 get_practice_user_list 函数开始。现在它什么都不返回
  • 它必须返回一些东西,即使那个东西是null
  • @LukeMills,是的,它正在返回null。就像我说的,当它从 get_user 函数返回时,if 块说它是空的,所以它打印“错误”

标签: php oop class object


【解决方案1】:

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

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

bind_param 的第一个参数应该是 'i' 而不是 's';

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

【讨论】:

  • 就像我说的那样,它填充在 get_user 函数中,但返回值不会显示在 get_practice_user_list
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-12-28
    • 2014-02-26
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2012-03-27
    • 2011-02-27
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多