What are the best practices for handling global variables and database connections within PHP functions?

When working with global variables and database connections within PHP functions, it is best practice to avoid using global variables as much as possible to prevent potential conflicts and improve code readability. Instead, pass variables as parameters to functions when needed. For database connections, consider using a database class or dependency injection to manage connections efficiently.

// Avoid using global variables
$globalVariable = 'value';

function exampleFunction($param1, $param2) {
    // Use parameters instead of global variables
    // Do something with $param1 and $param2
}

// Use a database class or dependency injection for database connections
class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
    }

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

// Example usage of database class
$database = new Database('localhost', 'username', 'password', 'database');
$result = $database->query('SELECT * FROM table');