Of course, this introduces state into your program (which is something one generally seeks to avoid). From a practical standpoint, if you ever need two database connections (two databases, or a privileged and an unprivileged user account (good for security), or re-using the class for another project), you won't be able to.
An alternative, if you don't like dependency injection, is to make your DB class act like a connection "library."
<?php
class mysqlilib extends mysqli{
# add static methods that manage your mysqli instance(s)
protected static $_connlib = [];
# use mysqlilib::get_conn() to (create, if necessary, and) get a mysqli instance from the library
public static function get_conn( $name,array $credentials=null ){
# "name" is an index so you can look up the connection you need
# check if there is already a matching mysqli instance
# something like
if( ! empty( self::$_connlib[$name] ) && (self::$_connlib[$name] instanceof mysqli) ){
return self::$_connlib[$name];
}
# "credentials" are the host, user, pass, etc. so you can create any connection you need.
# if $credentials is provided, use them to create a new mysqli
if( $credentials && self::set_conn( $name,$credentials ) ){
return self::$_connlib[$name];
}
return false;
}
# use mysqlilib::set_conn() to create a new mysqli instance in the library, without returning it
# (e.g., to set up your application's "default" connection,
# just do: mysqlilib::set_conn( 'default',['host','user','pass','dbname'] ); at the top of your script,
# then, any function can do: mysqlilib::get_conn( 'default' ); to use it.)
public static function set_conn( $name,array $credentials ){
# extract credentials from array (you'll probably want validation/error checking too)
list( $host,$user,$pass,$DBname ) = $credentials;
# try to create a new connection
$conn = new self( $host,$user,$pass,$DBname );
# if it worked, add it to the library
if( ! $conn->connect_errno ){
# success!
self::_connlib[$name] = $conn;
return true;
}else{
# there was a connection error
}
return false;
}
# you can override mysqli's __construct() method if you want to make sure you *never* end up with a connection that is not added to the library
private function __construct( $host,$user,$pass,$DBname,$port=null,$socket=null ){
return parent::__construct( $host,$user,$pass,$DBname,$port=null,$socket=null );
}
# add other methods as desired
}