gpt4 book ai didi

php - 从不在构造函数中实例化对象?

转载 作者:行者123 更新时间:2023-12-02 06:59:16 25 4
gpt4 key购买 nike

像下面这样在构造函数中实例化对象是否不好?

class Foo
{
public function fooMethod() {
return 'foo method';
}
}

class Too
{
public function tooMethod() {
return 'too method';
}
}

class Boo
{
public $foo;
public $too;

public function __construct()
{
$this->foo = new Foo();
$this->too = new Too();
}
}

如果是这样,它有多糟糕?应该如何正确完成?

最佳答案

在另一个类中手动实例化类会创建隐式依赖关系,这很难维护 - 如果您需要更改那些,您将很难检测到需要更改的内容 FooToo类。

因此,管理依赖关系的更好方法是:

class Foo
{
private $_bar;

function __construct(Bar $bar)
{
$this->_bar = $bar;
}
}

这样,您的对象依赖性就是显式的。这样做的另一个好处是,一些 PHP 框架(Laravel、Zend、Symfony)允许自动解决依赖关系。这意味着,你不需要手动实例化你的对象,只能通过某种工厂 - 就像这样(Laravel):

$foo = App::make('Foo');

还有一个 App工厂自动检测您的 Foo具有一些反射魔法的类依赖并适本地注入(inject)它们。其他框架也具有类似的功能。

此外,OOP 中还有一些通用原则,称为 SOLID这有助于开发更好的 OOP 设计。其中之一 - D , 代表 Dependency Inversion .这意味着,你应该避免 hard依赖项,就像在您的代码中一样。相反,FooBar类应该依赖于 interface ,像这样:

interface BarInterface
{
function doBar();
}

class Bar implements BarInterface
{
function doBar()
{
print "Doing BAR";
}
}

class Foo
{
/**
* @var BarInterface
*/
private $bar;

function __construct(BarInterface $bar)
{

$this->bar = $bar;
}
}

现在,如果您需要更改 Bar用别的东西上课,如果你的替代品也实现了BarInterface,那么一切都不会崩溃。 .

关于php - 从不在构造函数中实例化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25063059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com