当由另一个函数处理时,结果从PHP类查询返回错误

results return incorrectly from PHP class query when processed by another function

以下工作:

1
2
$user_list = new user_list();
$all_users_list = $user_list->getAllUsers();

以下内容不起作用,我不确定为什么不起作用:

1
$user_list = new user_list();

以上返回:

1
 Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, object given on line 59

参考类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class dbo extends mysqli {

    public function __construct(){
        require('config_db.inc.php');
        parent::__construct($db_host, $db_user, $db_pass, $db_name);

        if (mysqli_connect_error()) {
            die("Connect Error: (".mysqli_connect_errno().") -".mysqli_connect_error());
        }
    }



}

class user_list extends user {

    var $table_name ="cms_users";  

    function __construct($group ="") {
        if ($group =="") {
            return $this->getAllUsers();
        } else {
            $this->getUsersFromGroup($group);
            return $this->result;
        }
    }  

    function getAllUsers() {
        $dbh = new dbo();
        $sql ="SELECT * FROM {$this->table_name}";
        return $dbh->query($sql);
    }

    function getUsersFromGroup($group) {
        $dbh = new dbo();
        $sql ="SELECT * FROM {$this->table_name} WHERE group=$group";
        return $dbh->query($sql);
    }


}

问题是变量名$user_list的重用有不同的用途:

1
2
3
4
5
6
7
8
9
$user_list = new user_list();
// $user_list is now an object

$user_list = $user_list->getAllUsers();
// $user_list is now a mysqli resource

...

// line 59: code that expects $user_list to be a mysqli resource

比较:

1
2
3
4
5
6
$user_list = new user_list();
// $user_list is now an object

...

// line 59: code that expects $user_list to be a mysqli resource

不能从构造函数返回任何内容。new关键字将始终为您提供一个对象,从构造函数返回的值将一事无成。

你在if ($group ="")中也有一个错误,你的意思是if ($group =="")