Should the PDO object be passed as a parameter to functions handling database queries in PHP, or is there a better approach?

When handling database queries in PHP using PDO, it is a good practice to pass the PDO object as a parameter to functions that need to interact with the database. This helps in maintaining a clean separation of concerns and allows for better reusability of code. Alternatively, you can create a database class or a database connection class that encapsulates the PDO object and handles database interactions internally.

// Example of passing PDO object as a parameter to a function handling database queries
function getUsers(PDO $pdo) {
    $stmt = $pdo->query("SELECT * FROM users");
    return $stmt->fetchAll();
}

// Create a PDO connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Call the function passing the PDO object
$users = getUsers($pdo);