我已经阅读了关于依赖注入,我理解得很好,现在我有一个小问题,我正在制作一个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
}
}
所以我的问题是,如果不使用全局变量,我怎么能做同样的事情呢? (不必是依赖注入..)
答案 0 :(得分: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);
}
}