The best way to share database connection between classes

前端 未结 1 1724
悲&欢浪女
悲&欢浪女 2020-12-18 09:41

I would like to be able to hide my database connection from print_r so I am using a static variable. I have a base class and a few object classes. Ideally they would all sha

相关标签:
1条回答
  • 2020-12-18 09:52

    you can have a static method in your database class wich will return an instance of itself.

    $db = DB::getInstance();
    

    moreover you can implement a singleton pattern. you can read about it here.

    PHP Patterns

    The main idea is that you save your DB object in static property and then in getInstance check if it's set you return it or create new one, constructor should be made private so that the Object can't be created anywhere else but in getInstance.. this ensures that there is always one Instance of DB object.

    0 讨论(0)
提交回复
热议问题