What is the purpose of using a separate class for database connection in PHP applications?

Using a separate class for database connection in PHP applications helps to encapsulate the database-related functionality, making the code more organized and maintainable. It also allows for easier reuse of the database connection code across multiple parts of the application. Additionally, using a separate class makes it easier to switch between different database systems or configurations in the future.

class DatabaseConnection {
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'my_database';
    private $connection;

    public function __construct() {
        $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

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

// To use the database connection in your PHP application
$databaseConnection = new DatabaseConnection();
$connection = $databaseConnection->getConnection();