Auto connecting to PDO only if needed

前端 未结 5 2052
不思量自难忘°
不思量自难忘° 2020-12-17 04:27

I have a section of code that depending on the URL requested, will include one of fourteen other files. Some of these fourteen files require a connection to one of three di

5条回答
  •  甜味超标
    2020-12-17 04:38

    function &get_pdo()
    {
        static $_PDO = null;
    
        if ($_PDO === null)
        {
            $_PDO = new PDO('your DSN', 'username', 'password');
        }
    
        return $_PDO;
    }
    

    Then you just do

    $stmt = get_pdo()->prepare('...');
    

    You could do the same by extending the PDO class and adding a static singleton function to it. I find this approach simplier. Also gives you the opportunity to call it from anywhere on the stack without having to put your connection in the arguments (which can be good or bad, depending on the situation).

提交回复
热议问题