'Function for database connection with a static variable

Source: phptutorial.net/php-tutorial/php-registration-form/

Function db() connects the database once and returns a new PDO object with the configuration defined in another file.

function db(): PDO
{
    static $pdo;

    if (!$pdo) {
        return new PDO(
            sprintf("mysql:host=%s;dbname=%s;charset=UTF8", DB_HOST, DB_NAME),
            DB_USER,
            DB_PASSWORD,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );
    }
    return $pdo;
} 

The site says during the first call $pdo is not defined hence the statement inside if is executed and new PDO object is returned and during the second call the PDO object is returned since $pdo is a static variable. How does it not return a new PDO object again during the second call? Even if $pdo is static we have not assigned the PDO object to it. Wont it retain its null value?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source