全局vs函数vs静态类方法 [英] Global vs function vs static class method

查看:122
本文介绍了全局vs函数vs静态类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个对象是唯一的,它被所有其他类和函数使用... $ application

Let's say you have a object that is unique, and it's used by all other classes and functions ...something like $application.

如何在你的函数中访问这个对象?

How would you access this object in your functions?


  1. 您的功能:

  1. using a global variable in each of you functions:

global $application;
$application->doStuff();


  • 创建一个函数,例如 application $ c>将对象实例化为静态变量并返回它;然后在需要访问对象的任何位置使用此函数:

  • creating a function, like application() that instantiates the object into a static variable and returns it; then use this function everywhere you need to access the object:

    application()->doStuff();
    


  • 创建一个单例,类似于对象类中的静态方法, ,并使用此方法访问对象:

  • create a singleton thing, like a static method inside the object class which returns the only instance, and use this method to access the object:

    Application::getInstance()->doStuff();
    


  • KingCrunch& skwee:将应用程序对象作为参数传递到需要的每个函数/类

  • KingCrunch & skwee: Pass the application object as argument to each function/class where is needed

    ...
    public function __construct(Application $app, ...){
      ....
    


  • 如果有其他选项,请张贴他们。我想知道这些选项中哪一个是最有效/被认为是最佳实践。

    If there are other options please post them. I'm wondering which of these options is the most efficient / considered "best practice".

    推荐答案

    所有需要的方法。
    ie。

    I'd pass it to all the needed methods. i.e.

    function doFoo(Application $app) {
        $app->doStuff();
    }
    

    全局和单例都被认为是坏的,并且你的代码太多,测试比较困难。
    如果您对以下语句回答是,则允许使用singleton有一个规则:

    Both global and singleton considered bad and ties your code too much and this makes unit testing more difficult. There is one rule when you are allowed to use singleton, if you answer "yes" to the following statement:


    Do我需要向我的应用程序引入全局状态,我必须有一个给定对象的单个实例,并且有多个实例会导致错误

    如果你对所有3个部分回答yes,那么你可以使用singleton。在任何其他情况下,只需将所有实例传递给需要它们的所有方法。如果你有太多的,考虑使用像上下文

    If you answer yes to all the 3 parts then you can use singleton. In any other case just pass all the instances to all the method who needs them. If you have too much of them, consider using something like Context

    class Context {
        public $application;
        public $logger;
        ....
    }
    ========
    $context = new Context();
    $context->application = new Application();
    $context->logger = new Logger(...);
    doFoo($context);
    ========
    function doFoo(Context $context) {
        $context->application->doStuff();
        $context->logger->logThings();
    }
    

    (如果需要保护数据或操作

    (you can use getters/setters if you need to protect the data or manipulate it or if you want to use lazy initiation etc).

    祝你好运!

    这篇关于全局vs函数vs静态类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆