我编写了一些代码来从数据库中提取数据,然后将结果作为关联数组返回,但是我将返回值切换为一个对象(可以工作),但是当没有时,它不再在以下条件下失败结果存在。
if($myobject = MyClass::GetRecords("something")) {
// this code is now executing all the time
} else {
// this code no longer executes even when there are no results
}
class MyClass {
public static function GetRecords($myparam) {
$cn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$records = Array();
$query = '
SELECT
`' . DB_PREF . 'mytable`.`id`,
`' . DB_PREF . 'mytable`.`foo`,
`' . DB_PREF . 'mytable`.`bar`
FROM
`' . DB_PREF . 'mytable`
WHERE
`' . DB_PREF . 'mytable`.`bar`=?
';
if ($s = $cn->prepare($query)) {
$s->bind_param('s', $myparam);
$s->execute();
$result = $s->get_result();
while($row = $result->fetch_assoc()) {
$records[] = $row;
}
switch(count($records)) {
case 0:
$records = false;
break;
case 1:
$records = $records[0];
break;
}
$s->close();
} else {
// echo $cn->error;
}
mysqli_close($cn);
return (object)$records;
}
}
如果我执行return $records;
而非return (object)$records;
为什么这个条件失败或者我应该将$records
设置为什么以确保在我希望它失败时条件失败(例如,没有从数据库返回的记录)。目前,我将$records
设置为false
,因为这是失败条件的事实标准。
提前致谢。
答案 0 :(得分:1)
是的,如评论中所述,即使空的对象也被认为是真实的。
作为替代方案,只需添加一些逻辑:
if (!$records){
return false;
} else{
return (object)$records;
}