I'm trying to define a custom error handler for mysqli errors. Following my Database singleton:
<?php
class Database extends mysqli
{
private static $instance;
public function __construct($host, $user, $password, $database)
{
set_error_handler('self::error', MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $user, $password, $database);
}
public static function instance()
{
if (self::$instance === null) {
self::$instance = new self('example', 'example', 'example', 'example');
}
return self::$instance;
}
public static function error()
{
echo 'database error';
error_log('...');
exit();
}
}
Trying following code I don't see 'database error' on screen, and there aren't the three dots in the error log file:
<?php
include 'database.singleton.php';
$query = Database::instance()->prepare('wrong query');
$query->bind_param('si', $test, $test);
$query->execute();
$query->close();
Instead, there is the message Fatal error: Uncaught exception 'BadMethodCallException' with message 'Call to a member function bind_param() on a non-object (boolean)
in the errors log file. The error is true, because the query is deliberately wrong, so $query
is false, but I want to handle all mysqli errors with Database::error()
. I tried to replace set_error_handler('self::error', MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
to set_error_handler('self::error');
and also set_error_handler('self::error()');
but I don't see any difference. How can I solve?