Is there a use-case for singletons with database access in PHP?

后端 未结 11 1842
名媛妹妹
名媛妹妹 2020-11-21 06:44

I access my MySQL database via PDO. I\'m setting up access to the database, and my first attempt was to use the following:

The first thing I thought of is glob

11条回答
  •  一生所求
    2020-11-21 07:40

    When programming there is not "right" and "wrong"; there is "good practice" and "bad practice".

    Singletons are generally created as a class to be reused later. They need to be created in such a way that the programmer doesn't accidentally instantiate two instances while drunkenly coding at midnight.

    If you have a simple little class that shouldn't be instantiated more than once, you don't need to make it a singleton. It's just a safety net if you do.

    it's not always bad practice to have global objects. If you know that you're going to use it globally/everywhere/all the time, it may be one of the few exceptions. However, globals are generally considered "bad practice" in the same way that goto is considered bad practice.

提交回复
热议问题