我正在观看关于使用 php
开发留言簿的教程这是获取带有
的消息的代码public function GetMessage($id)
{
//Database
$id = (int)$id;
$gb_host = 'localhost' ;
$gb_dbname = 'guestbook' ;
$gb_username = 'root';
$gb_password = '' ;
$connection = mysqli_connect($gb_host , $gb_username , $gb_password,$gb_dbname);
$querycheck = mysqli_query($connection,"SELECT * FROM `messages` WHERE `id` = $id");
if($querycheck)
{
$message = mysqli_fetch_assoc($querycheck);
return $message;
}
else
{
mysqli_close($connection);
return NULL;
}
mysqli_close($connection);
}
为什么在else语句中我们返回NULL而不是False
Null和False有什么区别?
答案 0 :(得分:2)
类型。
False是布尔值,null是值。
所以:
$test = false;
if($test === false) {
//correct
}
$test = null;
if ($test === false) {
//incorrect
} else if ($test === null) {
//correct
}
$test = false;
if(!$test) {
//correct
}
$test = null;
if(!$test) {
//correct
}
更精确
答案 1 :(得分:1)
Imho in this case and null and false are incorrect, because method should return one type of data!
In our method it should be array not special type (null) or boolean, and it will be easy to use this method elsewhere, because everytime we know that we works with array, and we don't have write something like this:
$messages = $dao->GetMessage(27);
if (is_array($messages)) {
// ...
}
if (is_null($messages)) {
$messages = []; // because wihout it foreach will down
}
foreach ($messages as $message) {
// ...
}
And as for me it's pretty straightforward:
if we have data at db we'll receive not empty array,
if we don't have data at db - we'll receive empty array.
It's obviously!