Php 传递值的正确方法
假设我们有以下类,将类Php 传递值的正确方法,php,oop,design-patterns,Php,Oop,Design Patterns,假设我们有以下类,将类Foo的对象传递给Bar构造函数是否比只将参数baz和qux传递给Bar构造函数更好(就oop而言) class Foo { public $baz, $qux; public function __construct($baz, $qux) { $this->baz = $baz; $this->qux = $qux; } public function main() {
Foo
的对象传递给Bar
构造函数是否比只将参数baz
和qux
传递给Bar
构造函数更好(就oop而言)
class Foo
{
public $baz, $qux;
public function __construct($baz, $qux)
{
$this->baz = $baz;
$this->qux = $qux;
}
public function main()
{
$bar = new Bar($this);
//OR
$bar = new Bar($this->baz, $this->qux);
}
}
如果
Bar
类的对象在其构造函数中具有依赖项注入,则第一种情况是合理的:
class Foo
{
public $baz, $qux;
public function __construct($baz, $qux)
{
$this->baz = $baz;
$this->qux = $qux;
}
public function main()
{
$bar = new Bar($this);
//OR
//$bar = new Bar($this->baz, $this->qux);
}
}
class Bar
{
private $fooMembers = [];
public function __construct(Foo $foo_object)
{
// just for example
$this->$fooMembers[] = $foo_object->baz;
$this->$fooMembers[] = $foo_object->qux;
}
}
在我看来,就OOP而言,传递显式依赖项的选项要好得多:
class Foo
{
//...
public function main()
{
$bar = new Bar($this->baz, $this->qux);
}
}
在另一种情况下,直接实现GOD对象反模式。Bar
对象不需要Foo
,它需要Baz
和Qux
想象一下,您需要在Foo
之外创建条
:
$baz = new Baz();
$qux = new Qux();
$foo = new Foo($baz, $qux);
$bar = new Bar($foo);
你看到问题了吗?现在,您必须始终创建Foo才能创建Bar
更新:查看这篇文章,它更详细地解释了为什么您更喜欢直接传递依赖项。通常,传递参数更好,因为它们是显式的,并且代码易于阅读
但是,在某些情况下,论点太多或太复杂。以此为例:
public function __construct(arg1, arg2, arg3, arg4, arg5)
{
if (arg1 == 1)
{
$this->property1 = arg2;
$this->property2 = arg3;
} else {
$this->property1 = arg4;
$this->property2 = arg5;
}
}
在本例中,每个实例化只使用一些参数。这样定义构造函数会更简洁:
public function __construct(Foo $foo)
{
if ($foo->arg1 == 1)
{
$this->property1 = $foo->arg2;
$this->property2 = $foo->arg3;
} else {
$this->property1 = $foo->arg4;
$this->property2 = $foo->arg5;
}
}
它也做同样的事情,但在实例化点很容易阅读。在某些情况下,论证方案可能更为复杂
我建议阅读关于构建器设计模式的书籍。您将找到何时使用对象作为参数的示例。@Sougata我更喜欢公共函数\uuuuu构造(Foo$Foo){$this->Foo=$Foo}
稍后访问Foo
的属性。如果您需要所有属性,那么一切都可以,如果不需要,则传递特定属性更好。谢谢。我想知道使用前一种模式是否有什么好处?前一种模式:你能指出(指示)前一种模式吗?只将参数baz和qux传递给Bar构造函数,如果类Foo
的对象和类Bar
的对象最终将具有相同的属性集($baz
和$qux
)那么我看不出这种方法有什么好处。如果两个类是独立的-他们必须有不同的责任是的,面对的正是你所描述的情况。好吧,换成那个解决方案。