简体   繁体   中英

How to return instance of MYSQLi connection object from PHP function?

There is a problem when using MYSQLi connection object returned from the following PHP function (PHP version 5.3.10, MYSQL version 5.5.24):

function connectDB(){
  $con=new mysqli("host","user","password","database");
  return $con;
}

The function is called like this:

$mycon=connectDB();

The instance of connection object created with this method is not the same comparing to the one created directly without a function:

$mycon=new mysqli("host","user","password","database");

Output of

echo $mycon->host_info;

in the first case (with a function) is:

Localhost via UNIX socket

and in the latter case (without a function):

LOCALHOST via TCP/IP

Is something wrong with such method of creating a connection?

I've found the mistake. The connection was actually made with variables:

$con=new mysqli($host,$user,$password,$database);

I've omitted variables in the question thinking they were unnecessary details. And it turned out that variables were defined out of the function scope. Connection was created with undefined arguments, I guess with default settings. The thing to note is that there were no warnings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM