How can global variables impact the functionality of PHP functions, especially in relation to database connections?

Global variables can impact the functionality of PHP functions by making the code harder to maintain and debug. In the case of database connections, using global variables can lead to potential security risks as the connection details are exposed throughout the code. It is recommended to pass database connection details as parameters to functions or use a singleton pattern to manage the database connection.

// Using a singleton pattern to manage the database connection

class Database {
    private static $instance = null;
    private $connection;

    private function __construct() {
        $this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    }

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

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

// Example of using the database connection in a function
function getUsers() {
    $db = Database::getInstance();
    $connection = $db->getConnection();

    $stmt = $connection->query('SELECT * FROM users');
    return $stmt->fetchAll();
}

// Call the function
$users = getUsers();