The best way to share database connection between classes

孤人 提交于 2019-12-18 05:10:30

问题


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 share the same database connection. What is the best way of sharing this? The way I have it set up now "works" but it just doesnt feel right. Must be a better way of doing this. (logically the classes shouldnt inherit one another)

class base {

  private static $db;

  function __construct() {

    self::$db = new DB(); // our database class
    $foo = new Foo( self::$db ); // some other class that needs the same connection

  }

}

class Foo {

  private static $db;

  function __construct( $db ) {
    self::$db = $db;
  }

}

回答1:


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.



来源:https://stackoverflow.com/questions/5596251/the-best-way-to-share-database-connection-between-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!