在构造函数中调用多个$ this

时间:2014-07-26 17:13:56

标签: php

您好可以在$this中拨打多个single __construct()吗?我是

PHP OOP和MVC相对较新。因为我想在

中调用一个函数

功能所以我想到了使用下面的代码。 <还有其他方法

做得比这更好吗?

//maincontroller.php
class MainController{
   public $controller2;
   public $controller3;

   function __construct(){
      $this->controller2 = new Controller2();
      $this->controller3 = new Controller3();
   }
}

//controller2.php
class Controller2{

}

//controller3.php
class Controller3{

}

1 个答案:

答案 0 :(得分:0)

使用依赖注入:

//controller2.php
class Controller2{

}

//controller3.php
class Controller3{

}

//maincontroller.php
class MainController{
   public $controller2;
   public $controller3;

   function __construct(Controller2 $controller2, Controller3 $controller3){
      $this->controller2 = $controller2;
      $this->controller3 = $controller3;
   }
}

$controller2 = new Controller2();
$controller3 = new Controller3();
$controller = new Controller($controller2, $controller3);

虽然类型提示仍然是特定的类而不是接口:如果你的控制器实现了一个接口会更好