douzhi2760 2016-07-05 15:58
浏览 22

PHP类在多个声明上的性能

Let's say I have a huge class named Foo. if I have to call this class several times in different classes, what is the best way to use it?

Note: Bar is not the only class that will use Foo.

Option #1 (create object when its needed):

class Bar
{
    public function myMethod($arg)
    {
        $foo = new Foo();
        $something = $foo->doSomething($arg);

        return $something;
    }
}

Option #2 (create it once):

class Bar
{
    protected $foo;

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

Option #3 (make Foo static):

class Bar
{
    public function myMethod($arg)
    {
        return Foo::doSomething($arg);
    }
}

Option #4:

// tell me the proper way to do it

  • 写回答

1条回答 默认 最新

  • douping6871 2016-07-05 16:05
    关注

    The best way I'd say is to instantiate Foo outside the Bar class and inject it as a dependency - the best way to do this would be via constructor:

    class Bar
    {
        private $foo;
    
        public function __construct(Foo $foo)
        {
            $this->foo = foo;
        }
    }
    
    $foo = new Foo();
    $bar = new Bar($foo);
    

    Then do the same for all classes that have Foo as a dependency. You can reuse the instance if it is suitable or you can create a new one if needed.

    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接