What is the best practice for passing a MySQL connection variable to functions in PHP?

When passing a MySQL connection variable to functions in PHP, it is best practice to use dependency injection. This means passing the connection variable as a parameter to the function that needs it, rather than relying on global variables. This approach makes the code more modular, testable, and easier to maintain.

// Establish MySQL connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Function that requires MySQL connection
function fetchData($conn) {
    $sql = "SELECT * FROM table";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "Name: " . $row["name"] . "<br>";
        }
    } else {
        echo "0 results";
    }
}

// Call the function with the MySQL connection
fetchData($conn);

// Close the MySQL connection
$conn->close();