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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算