将实例化对象转移到类中

问题描述 投票:0回答:1

我想知道将实例化对象转移到另一个类以供本地使用的最佳方法是什么。如果这在内存使用方面存在差异,我也很好奇。

我想,主要有两种方式:

1.)通过引用$ GLOBALS传输实例化对象:

class UserLogHandler {
  public function __construct() {
    $this->DB = $GLOBALS['DB'];
    $this->Security = $GLOBALS['Security'];
  }
  public function doSomeWork() {
    $this->DB->someMethod;
  }
}

或2.)通过移交转移:

class UserLogHandler($DB,$Security) {
    public function doSomeWork() {
        $DB->someMethod;
    }
}

在我看来,选项2可能更适合复杂的环境,尽管我发现选项1更具吸引力。无论如何,我更喜欢技术和/或逻辑解释为什么使用一个选项而不是另一个。如果还有其他更好的选择,请告诉我。

托马斯,先谢谢你,祝福

php object transfer globals
1个回答
0
投票

这确实是个好问题。我会说这取决于你的需要。让我们逐一分析您的选择。

在开始之前,请记住,您的对象应始终是一个完整的对象。它不应该是一个不完整的状态。您可以参考这篇文章以获得更多了解https://matthiasnoback.nl/2018/07/objects-should-be-constructed-in-one-go/

1.)通过引用$ GLOBALS传输实例化对象:

你绝不能使用这些方法,因为它们令人困惑。 $ GLOBALS缺乏告诉您特定变量的创建位置和方式,因此您无法确定此变量是否存在或存在的变量。我建议你使用依赖注入

use DB;
use Security;

class UserLogHandler
{
    public function __construct(DB $DB, Security $Security)
    {
        $this->DB = $DB;
        $this->Security = $Security;
    }

    public function doSomeWork()
    {
        $this->DB->someMethod;
    }

}

看看你现在如何确保从注入的$ DB和$ Security以及它们持有的内容。您甚至可以使用Security $Security等类型指示强制执行变量类型。

当您的类很大程度上依赖于特定变量时,此方法很方便。例如模型类总是需要DB适配器或PDF生成器库本质上需要PDF类。

2.)通过移交转移

这可以按照你的预期工作,但我认为你在定义它时犯了错误。你需要像下面这样写。

class UserLogHandler
{
    public function doSomeWork($DB, $Security)
    {
        $DB->someMethod;
    }
}

当您仅在特定函数中需要特定变量时,此方法很方便。它的示例,就像我们需要从某个特定条件的模型中获取记录。因此我们可以在函数中传递值并根据值获得结果。

use DB;
use Security;

class UserLogHandler
{
    public function __construct(DB $DB, $Security)
    {
        $this->DB = $DB;
        $this->Security = $Security;
    }

    public function doSomeWork($value)
    {
        if ($value = 'something') {
            $this->DB->someMethod;
        }
    }

}

如您所见,两种方法都可用于共轭。它只取决于你的要求

© www.soinside.com 2019 - 2024. All rights reserved.