PHP: Database Connection Class Constructor Method

前端 未结 6 1026
旧巷少年郎
旧巷少年郎 2021-02-03 16:19

I\'m new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was t

6条回答
  •  花落未央
    2021-02-03 17:06

    The latter is probably better, but with an adjustment: pass some arguments to the constructor, namely the connection info.

    Your first example is only useful if you've got one database connection and only if you're happy hard-coding the connection values (you shouldn't be). The second example, if you add say, a $name parameter as an argument, could be used to connect to multiple databases:

    I'm new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was told this is bad style and should be avoided.

    class DatabaseConnection {
        private $dbHost;
        private $dbUser;
        private $dbPass;
        private $dbName;
    
        function __construct($config) {
            // Process the config file and dump the variables into $config
            $this->dbHost = $config['host'];
            $this->dbName = $config['name'];
            $this->dbUser = $config['user'];
            $this->dbPass = $config['pass'];
    
            $connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
                or die("Could not connect to the database:
    " . mysql_error()); mysql_select_db($this->dbName, $connection) or die("Database error:
    " . mysql_error()); } }

    So using this style, you now have a more useful class.

提交回复
热议问题