What are the advantages of recycling connection objects in PHP scripts?

When writing PHP scripts that interact with databases, it is important to recycle connection objects to improve performance and reduce resource consumption. By reusing the same connection object instead of creating new ones for each database query, you can avoid the overhead of establishing a new connection each time. This can lead to faster execution times and more efficient memory usage in your scripts.

// Create a function to establish a database connection and reuse it
function getDBConnection() {
    static $connection = null;
    
    if ($connection === null) {
        $connection = new mysqli('localhost', 'username', 'password', 'database');
        
        if ($connection->connect_error) {
            die("Connection failed: " . $connection->connect_error);
        }
    }
    
    return $connection;
}

// Example usage of the recycled connection object
$connection = getDBConnection();
$result = $connection->query("SELECT * FROM table_name");
// Process the query result