Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

php - The best way to share database connection between classes

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;
  }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...