What are some best practices for passing database connections as parameters in PHP functions?
When passing database connections as parameters in PHP functions, it is important to ensure that the connection is established before passing it and closed after its use to prevent resource leaks. It is also recommended to use dependency injection to pass the connection object to functions, rather than creating a new connection within the function itself. This helps in keeping the code modular and testable.
// Establish a database connection
$connection = new mysqli('localhost', 'username', 'password', 'database');
// Function that takes database connection as parameter
function fetchData($connection) {
$query = "SELECT * FROM table";
$result = $connection->query($query);
// Process the result
// Close the connection
$connection->close();
}
// Call the function with the database connection
fetchData($connection);