What are some best practices for managing MySQLi objects in PHP classes for reusability?

When managing MySQLi objects in PHP classes for reusability, it is important to properly encapsulate the database connection logic within the class to ensure clean and maintainable code. One way to achieve this is by creating a separate method within the class to establish the database connection and return the MySQLi object when needed. This allows for easy reusability of the database connection throughout the class without duplicating code.

class Database {
    private $conn;

    public function __construct($host, $username, $password, $dbname) {
        $this->conn = new mysqli($host, $username, $password, $dbname);

        if ($this->conn->connect_error) {
            die("Connection failed: " . $this->conn->connect_error);
        }
    }

    public function getConnection() {
        return $this->conn;
    }
}

// Example usage
$db = new Database('localhost', 'username', 'password', 'database');
$conn = $db->getConnection();