What are the best practices for passing database instances to functions in PHP to avoid errors like "Call to a member function query() on a non-object"?

When passing database instances to functions in PHP, it's important to ensure that the instance is properly initialized and passed as a parameter to avoid errors like "Call to a member function query() on a non-object". One way to solve this issue is by checking if the database instance is valid before calling any methods on it within the function.

// Incorrect way of passing database instance to a function
function fetchData($db) {
    $result = $db->query("SELECT * FROM table"); // This may cause "Call to a member function query() on a non-object" error
    return $result->fetchAll();
}

// Correct way of passing database instance to a function
function fetchData($db) {
    if ($db instanceof PDO) {
        $result = $db->query("SELECT * FROM table");
        return $result->fetchAll();
    } else {
        return false;
    }
}

// Usage
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$data = fetchData($pdo);