PHP: Database Connection Class Constructor Method

前端 未结 6 1015
旧巷少年郎
旧巷少年郎 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 16:52

    First of all: this is pointless.

    You are creating an object wrapper for the 10+ year old mysql_* function. This php extension is no longer maintained and the process of deprecation has already begun. You should not use this API for any new projects in 2012.

    Instead you should learn how to use PDO or MySQLi and work with prepared statements.

    That said .. lets take a look at your code:

    • Constructor should receive all the parameters required for creating new instance, parameters should not be hard-coded in the class definition. What if you need to work with two databases at the same time ?
    • When connection is created, it should be stored in object's scope variable. Something along the lines of $this->connection = mysql_conn.... Instead you store it in local variable, which you "loose" right after constructor is done.
    • You should not use private variables for everything. They are not visible to classes which would extend your original class. Unless it is intentional, you should choose protected for this.
    • The or die('..') bit most go. Do not stop the whole application if connection fails. Instead you should throw an exception, which then can be handled outside of the constructor.

提交回复
热议问题