0

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?

  • 1
    I have to agree with you, this is weird. Have you tried it? – KIKO Software Mar 10 '22 at 09:45
  • Not yet. I got stuck trying to understand this. – brittle_spirit Mar 10 '22 at 09:47
  • 1
    Well, if it doesn't do what the author says it will create a new connection every time, so it will still work, but very inefficiently. You can put an `echo "I made a new connection";` after the `if (!$pdo) {` to see if it does indeed make a new connection every time. I think it will. – KIKO Software Mar 10 '22 at 09:50
  • 2
    Yes, it's a bug in the author's code. – deceze Mar 10 '22 at 09:52
  • The whole thing makes no sense. Maybe this is what was intended: https://3v4l.org/pt5P1 . Seems like they didn't test their own code properly. – ADyson Mar 10 '22 at 10:24
  • $pdo is never assigned, so how could it retain ANY value. https://3v4l.org/40rqv It will just keep creating new connections when called. – mickmackusa Mar 10 '22 at 10:45
  • Similar in intent: https://stackoverflow.com/a/67682706/2943403 – mickmackusa Mar 10 '22 at 10:51

0 Answers0