dsgdg54ef4365 2014-08-14 23:39 采纳率: 0%
浏览 46
已采纳

php对象交互 - 在其他实例中调用实例

I created a simple database connection class:

class db {

private $db_host = "host";
private $db_user = "user";
private $db_pass = "pass";
private $db_name = "db_name";

public $con;

public function __construct() {
    $this->con = mysqli_connect($this->db_host, ... );
   ...
}

public function query($query) {
   return mysqli_query($this->con,$query);
}
}

Now, I would like to use $db->query() within another class instance:

class display {

public function menu() {
this function creates a list based on a result of $db->query('SQL query')
}
plus various other functions to display different things, all using $db->query()

So what is the problem?

First, I got this working by adding 'global $db' to $disply->menu() but this is obviously a big NO NO and needs to be specified within each method.

It is probably clear now that I would like to use $db->query(SQL query) wherever and whenever I need an SQL result, not just within the global scope.

I spent the last couple of hours looking this up but to my surprise most people ask how to use something like $instance->instance->method in global.

Many thanks for your time.

Tom

  • 写回答

1条回答 默认 最新

  • duandong2562 2014-08-14 23:45
    关注

    A simple solution is to inject the $db object when you instance your classes

    class Display {
    
        protected $db;
    
        public function __construct($db) {
           $this->db = $db;
        }
    
        public function menu() {
            // here you can use $this->db as if it was the global $db;
        }
    }
    

    You need to add $db as a parameter everytime you instance your classes

    $mydisplay = new Display($db);
    

    There are other ways to achieve the same purpose. For example you can make the $db class a singleton, and add a static method to retrieve the instance from wherever you need. And there are more sophisticated ways such as using pimple to manage your dependency injections as a provider instead of doing it manually.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao