我了解依赖注入(例如数据库)背后的基本概念,但我不知道如何在静态函数中使用它:
class Foo{
private $id;
private $class_variables,...;
private $db;
public function __construct($db,$id,$class_varibles,...)
{
$this->db=$db;
//Assignments
}
public static function Get_By_ID($id)
{
//No DB-Connection here
return new Foo(?);
}
}只有这样才能做到这一点吗?
class Foo{
...
public static function Get_By_ID($db,$id)
{
//Do work here!
return new Foo($db,$id,$class_variables,...);
}对于一些静态函数来说,这似乎是一项额外的工作。另外:
$f = new Foo($db);将只能使用保存在其中的"$db“(私有$db)创建新对象。
$b = $f->Create_Bar();你怎么能解决这个问题?是唯一的办法:
$b = $f->Create_Bar($db_for_bar);附加:如何使用静态函数完成它?
$b = Foo::Create_Bar($db_for_foo,$db_for_bar);我遗漏了什么?
(增加2:
$f = new Foo($db); //Dependency Injection ($db is saved in $f, and is the database-link for example)
$f->Create_Bar($db_for_bar); //OK - No Problem但是如果"Create_Bar“在"Foo”中被称为“Foo”呢?
$this->Create_Bar(???) //Where does the $db_for_bar come from?)
发布于 2013-10-15 07:49:09
这是一个很好的解决方案,我不明白你为什么说它不起作用:
class Foo{
...
public static function Get_By_ID($db,$id)
{
return new Foo($db,$id,$class_variables,...);
}https://stackoverflow.com/questions/19375147
复制相似问题