0

我已经阅读了有关依赖注入的内容,我理解得很好,现在我遇到了一个小问题,我正在制作一个包含很多类(成员、游戏、帖子等)的 oop 站点结构。由于很多人告诉我不建议为此目的使用全局变量,所以我遇到了这个小问题。例如:

$mysql_connection = ...connection
$members = new Members($mysql_connection); //i need to implement posts and games 
$posts = new Posts($mysql_connection); //i need to implement members
$games = new Games($mysql_connection); //i need to implement members

当我使用全局变量传递类时,类的顺序并不那么重要:

global $connection;
$connection = ...connection

global $members;
$members = new Members();

global $posts;
$posts = new Posts();

etc...

一个类的例子:

class Posts{

 function getMemberPosts($id){
    ...implementing the globals
    global $connection, $members;
    ...using the globals
 }

}

所以我的问题是,我如何在不使用全局变量的情况下做同样的事情?(不一定是依赖注入..)

4

1 回答 1

0

您想要存储和使用注入的组件,而不是全局组件。

class Posts{
    protected $dbconnection;

    public function __construct($dbconn){
       // save the injected dependency as a property
       $this->dbconnection = $dbconn;
    }

    public function getMemberPosts($id, $members){
       // also inject the members into the function call

       // do something cool with members to build a query

       // use object notation to use the dbconnection object
       $this->dbconnection->query($query);
    }

}
于 2013-07-15T18:11:08.130 回答