-2

我有功能:

function dbConnect($usertype, $connectionType = 'mysqli') {

   // some code hare

   return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}

但是当我尝试这个时:

$conn = dbConnect('read');
$result = $conn->query('SELECT * FROM images');

函数不返回任何东西,它说:

致命错误:在第 10 行的 C:\xampp\htdocs\phpsols\mysql\mysqli.php 中的非对象上调用成员函数 query()

但它是这样工作的(没有死())

return new mysqli($host, $user, $pwd, $db);
4

3 回答 3

5

[..] or die()构造与 return 语句一起导致了有趣的行为:整个事情被解释为一个布尔表达式。

并且因为new mysqli永远不会为假,所以永远不会处理“die”,因此,您的函数返回true而不是新创建的mysqli.

如果您仍想使用or die(),请执行以下操作:

$result = new mysqli($host, $user, $pwd, $db) ;
if (!$result) die ("Can't open database.");
return $result;
于 2013-08-21T08:23:35.723 回答
1

你可以试试这个:

function dbConnect($usertype, $connectionType = 'mysqli') {

   // some code hare
   try {
       return new mysqli($host, $user, $pwd, $db);
   } catch(Exception $e) {
       die ('Cannot open database');
   }
}
于 2013-08-21T08:34:52.453 回答
-2

aside from this funny one-liner problem, your idea of error handling is all wrong. Sadly, it was copy-pasted to other answer as well.

Here is the right code

$mysqli = new mysqli($host, $user, $pwd, $db);
if ( mysqli_connect_errno() )
{
    throw new Exception(mysqli_connect_errno()." ".mysqli_connect_error());
}
return $mysqli;

Honestly, this die ('something'); thing is a childhood disease of PHP. Time to grow up a little.

于 2013-08-21T08:31:30.880 回答