在类之间共享数据库连接的最佳方式 [英] The best way to share database connection between classes

查看:101
本文介绍了在类之间共享数据库连接的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够从print_r隐藏我的数据库连接,所以我使用一个静态变量。我有一个基类和几个对象类。理想情况下,它们将共享相同的数据库连接。什么是最好的分享方式?
我设置的方式现在工作,但它只是不觉得正确。必须是一个更好的方法这样做。
(逻辑上这些类应该彼此继承)

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

}


推荐答案

你可以在你的数据库类中有一个静态方法,它将返回一个自己的实例。

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模式

主要想法是将您的数据库对象保存在静态属性中,然后在getInstance中检查是否设置了返回它或创建新的一个,构造函数应该是私有的,所以对象不能在任何其他地方,但在getInstance中创建..这确保总是有一个实例的DB对象。

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.

这篇关于在类之间共享数据库连接的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆