Is it advisable to create a separate class for database connections in PHP, or is it more efficient to directly use PDO or MySQLi in the main classes?

It is advisable to create a separate class for database connections in PHP for better organization, reusability, and maintainability of your code. This approach also helps in adhering to the principles of object-oriented programming. By encapsulating the database connection logic in a separate class, you can easily switch between different database drivers (e.g., MySQL, PostgreSQL) without affecting the main classes that interact with the database.

<?php
class Database {
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'my_database';
    private $connection;

    public function __construct() {
        $this->connection = new PDO("mysql:host=$this->host;dbname=$this->database", $this->username, $this->password);
        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

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

// Example of using the Database class
$database = new Database();
$connection = $database->getConnection();
// Perform database operations using $connection
?>