2013-08-23 04:21
浏览 23


I am building an API in PHP and I have a question. I'm using classes, and some of these classes need to access my database. However, I don't want to define variables for the database in every single class in order to open it, or have to send my mysqli object as a parameter of every single class constructor.

What would be the best way to go about this? Do I define a global variable of some kind?

图片转代码服务由CSDN问答提供 功能建议

我正在用PHP构建API,我有一个问题。 我正在使用类,其中一些类需要访问我的数据库。 但是,我不想在每个类中为数据库定义变量以便打开它,或者必须将我的mysqli对象作为每个类构造函数的参数发送。

最好的方法是什么? 我是否定义了某种全局变量?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dr5648 2013-08-23 06:24

    A classic solution would be as follows

    1. Create an instance of dbatabase handler class, either raw mysqli (worse) or better abstraction class (way better)
    2. In the constructor of your application class take this db class instance as a parameter and assign it to a local variable
    3. Use this variable with your class.

    A quick example:

    class Foo()
        protected $db;
        function __construct($db);
            $this->db = $db;
        function getBar($id)
            return $this->db->getOne("SELECT * FROM bar WHERE id=?i", $id);
    $db = new safeMysql();
    $foo = new Foo($db);
    $bar = $foo->getBar($_GET['id']);
    解决 无用
    打赏 举报
  • dtq81142 2013-08-23 04:36

    How about using a static classes?

    class mysqli_wrapper {
    private static $db = null;
    public static function open() {
        GLOBAL $opts; // this can be global or setup in other ways
        if (!self::$db) {
            self::$db = null;
        self::$db = @mysqli_connect('p:'.$opts['hn'], $opts['un'], $opts['pw'], $opts['db']);
        return self::$db;
    public static function query($qry) {
        return mysqli_query ( self::$db, $qry );
    public static function affected_rows() { return @mysqli_affected_rows(self::$db); }
    public static function error() { return @mysqli_error(self::$db); }
    public static function close() { @mysqli_close(self::$db); }
    } // end mysqli_wrapper
    mysqli_wrapper::open(); //  Here's how to call it
    解决 无用
    打赏 举报
  • dongpan1871 2013-08-23 04:51

    In a system I maintain my app needs to access its own MySQL db, as well as remote Oracle and SQL Server databases, and I use a trait for it. Here's a simplification of my code, just using MySQL:


    trait DatabaseAccess {
        protected $db;
        private $host = 'host', $dbName = 'db', $username = 'username', $password = 'pword';
        public function connectToMysql() {
             $this->db= new mysqli(......);

    then in myclass.php

    require 'dbaccess.php'; 
    class MyClass {
        use DatabaseAccess;
        //class code.....

    All elements of DatabaseAccess will be available as if you hand-typed them in MyClass. Note: if you're using PHP < 5.4, then this solution won't be possible.

    解决 无用
    打赏 举报

相关推荐 更多相似问题