I am extending a class from mysqli, but I am not sure if I am doing correctly when I want to close the db connection:
class database extends mysqli
{
public function __construct($hostname = null,$username= null,$password = null,$database = null,$port = null, $socket = null)
{
$hostname = $hostname !== null ? $hostname : ini_get("mysqli.default_host");
$username = $username !== null ? $username : ini_get("mysqli.default_user");
$password = $password !== null ? $password : ini_get("mysqli.default_pw");
$database = $database !== null ? $database : "";
$port = $port !== null ? $port : ini_get("mysqli.default_port");
$socket = $socket !== null ? $socket : ini_get("mysqli.default_socket");
parent::__construct($hostname,$username,$password,$database,$port,$socket);
# Check for connection error
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
#closes the database connection when object is destroyed.
public function __destruct()
{
return parent::close();
//echo "Destructor Called";
}
}
do I have put return in front of parent::close();?
return parent::close();
or this will do?
public function __destruct()
{
parent::close();
}
Thanks.
The idea with a destructor is that it is automatically called when the object goes out of scope. As such, there will be nothing to assign a return value to.
The best practice is for destructors (and constructors) to not return anything (void).
Program code should never call the destructor directly.
Edit: So to directly answer your question, use your second example
Regarding exceptions, try something like this in your constructor
To catch the exception, simply use a try / catch block, eg