How can PHP developers ensure clean and efficient code when working with database connections in multiple files?

When working with database connections in multiple files, PHP developers can ensure clean and efficient code by using a singleton pattern to create a single instance of the database connection object that can be shared across different files. This approach helps avoid creating multiple connections to the database, which can lead to inefficiency and potential resource wastage.

// Create a Database class with a static method to establish a connection
class Database {
    private static $connection;

    public static function getConnection() {
        if (!self::$connection) {
            self::$connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
        }
        return self::$connection;
    }
}

// In each file that needs to interact with the database, use the getConnection method
$connection = Database::getConnection();
$stmt = $connection->prepare("SELECT * FROM users");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);