dsuvs66406 2013-03-06 17:07
浏览 14
已采纳

PHP - 两个类,正确地相互交谈

I have a small problem. I've tried searching, but I can't get the search terms quite right and was hoping someone could help.

I have an include on every page in my system that works something like this:

<?PHP
require_once("class.system.php");
require_once("class.mysql.php");

$oMySQL = new MySQL();
$oSystem        = new SystemClass();

... ?>

But I have a problem. As you may guess - the MySQL class is a bunch of functions that I use to make MySQL calls easier. This isn't the only example of where I want to use it but it's a good example.

I have functions in the system class I want to be able to reference the MySQL class (And vice versa...).

As an example, I have a function in the system class that will populate a session variable with data from MySQL. The only way I can think of doing this (Which I know is wrong...) is:

class SystemClass {

    function PopulateSession(){
         global $oMySQL;
         if($oMySQL->Select('abc')){
             $_SESSION['def']= blahblahblah;
             return true;
         } else {
             return false;
         }
    }
}

It works, but it means every function I want to use it, I have to use global, which I'm sure is very bad practice. Could someone advise??

Thanks

  • 写回答

1条回答 默认 最新

  • duanmeng1862 2013-03-06 17:08
    关注

    What you encountered is called composition. A good solution would be to use a dependency injection framework. An easy solution is to roll with constructor parameters.

    public class A { 
      private $b;
      public function __construct($b) {
        $this->b = $b;
      }
    }
    
    $b = new B;
    $a = new A($b); 
    

    Or, as a more flexible solution, when you have mutual dependencies:

    public class A {
      private $b;
      public function setB($b) {
        $this->b = $b;
      }
    }
    
    public class B {
      private $a;
      public function setA($a) {
        $this->a = $a;
      }
    }
    
    $a = new A;
    $b = new B;
    $a->setB($b);
    $b->setA($a);
    

    But the downside is that as the number of dependencies grows, it's hard to manage and remember to set all the dependencies. This is exactly the reason why Dependency Injection frameworks are popular.

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

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀