What are the potential reasons for the error "Fatal error: Call to a member function close() on a non-object" in PHP code, and how can it be fixed?

The error "Fatal error: Call to a member function close() on a non-object" occurs when trying to call the close() method on a variable that is not an object. This can happen if the variable is not properly initialized or if the object creation failed. To fix this error, ensure that the variable is assigned an object instance before calling its methods.

// Incorrect code that may result in the error
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
$result = $connection->query("SELECT * FROM table");
$connection->close();

// Corrected code to prevent the error
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
if($connection) {
    $result = $connection->query("SELECT * FROM table");
    $connection->close();
} else {
    echo "Failed to connect to database.";
}