Trying to build a static database class that I can access from any function outside of the class

前端 未结 1 1897
青春惊慌失措
青春惊慌失措 2020-12-21 18:16

UPDATED: Changed code to the now working class code using PDO instead of deprecated methods

The original question was answered and the prob

相关标签:
1条回答
  • 2020-12-21 19:18

    In order for your class to operate statically, you need to do a few things.

    First, make the connection static, eg

    private static $connection;
    

    Secondly, why all the underscores?

    define('DB_HOST', 'localhost');
    define('DB_NAME', 'your_db_name');
    define('DB_USER', 'username');
    define('DB_PASS', 'password');
    

    Also, why use class constants at all? Just use the constants you've already defined.

    Third, lose the constructor. You cannot expect to create an instance of this class and use it statically. I would go for a lazy-load approach for the connection

    private static function getConnection() {
        if (self::$connection === null) {
            $dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8',
                DB_HOST, DB_NAME);
    
            self::$connection = new PDO($dsn, DB_USER, DB_PASS, array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ));
        }
        return self::$connection;
    }
    

    Then, your public methods would call this method internally. I'll also flesh out your dbDataArray method to show you how to return an associative array

    public static function dbDataArray($query, $params = array()) {
        $stmt = self::getConnection()->prepare($query);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
    
    0 讨论(0)
提交回复
热议问题