What are the scope considerations when working with variables in PHP and MySQL connections?

When working with variables in PHP and MySQL connections, it's important to consider the scope of the variables to ensure they are accessible where needed. To ensure proper scope, declare variables outside of functions or loops if they need to be accessed globally, and pass variables as parameters to functions when needed inside them. Additionally, be mindful of variable naming conflicts to avoid unexpected behavior.

// Declare variables outside of functions for global access
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Pass variables as parameters to functions
function connectToDatabase($servername, $username, $password, $dbname) {
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    return $conn;
}

// Example usage
$conn = connectToDatabase($servername, $username, $password, $dbname);