doujia1988 2013-08-23 04:21
浏览 23
已采纳

使用mysqli的类

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?

  • 写回答

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']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作