什么时候应该使用静态方法? [英] When should I use static methods?

查看:73
本文介绍了什么时候应该使用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含10个方法的类. 我总是需要使用其中一种方法.现在我想知道哪种方法更好?

I have a class that is containing 10 methods. I always need to use one of those methods. Now I want to know, which approach is better?

class cls{
    public function func1(){}
    public function func2(){}
    .
    .
    public function func10(){}
}

$obj  = new cls;
$data = $obj->func3(); // it is random, it can be anything (func1, or func9 or ...)

OR

class cls{
    public static function func1(){}
    public static function func2(){}
    .
    .
    public static function func10(){}
}

cls::func3(); // it is random, it can be anything (func1, or func9 or ...)

推荐答案

这是一个有趣的主题.我要给你一个面向设计的答案.

It is an interesting subject. I'm gonna give you a design oriented answer.

我认为,永远不要在良好的OOP体系结构中使用静态类/函数.

In my opinion, you should never use a static class/function in a good OOP architecture.

使用static时,这是在没有类实例的情况下调用函数.主要原因通常是代表一个不应多次实例化的服务类.

When you use static, this is to call a function without an instance of the class. The main reason is often to represent a service class which should not be instantiated many times.

我将为您提供3种解决方案(从最差到最好):

I will give you 3 solutions (from the worst to the best) to achieve that:

静态

静态类(仅具有静态函数)使您无法使用许多OOP功能,例如继承,接口实现.如果您真的想到了什么是静态函数,那么它就是一个由其类名命名的函数.您已经在PHP中有了名称空间,那么为什么还要添加另一层呢?

A static class (with only static functions) prevent you from using many OOP features like inheritance, interface implementation. If you really think of what is a static function, it is a function namespaced by the name of its class. You already have namespaces in PHP, so why add another layer?

另一个很大的缺点是,您无法使用静态类和使用它的类定义明确的依赖关系,这对应用程序的可维护性和可伸缩性是不利的.

Another big disadvantage is that you cannot define clear dependencies with your static class and the classes using it which is a bad thing for maintenability and scalability of your application.

单人

单例是一种强制类仅具有一个实例的方法:

A singleton is a way to force a class to have only one instance:

<?php

class Singleton {
    // Unique instance.
    private static $instance = null;

    // Private constructor prevent you from instancing the class with "new".
    private function __construct() {  
    }

    // Method to get the unique instance.
    public static function getInstance() {
        // Create the instance if it does not exist.
        if (!isset(self::$instance)) {
            self::$instance = new Singleton();  
        }

        // Return the unique instance.
        return self::$instance;
    }
}

这是一种更好的方法,因为您可以使用继承,接口,并且将在实例化的对象上调用您的方法.这意味着您可以定义合同,并将低耦合与使用它的类一起使用.但是,有些人认为单例是反模式,尤其是因为如果您想要拥有两个或两个以上具有不同输入属性的类实例(例如连接2个不同数据库的经典示例),就不能不使用单例对所有代码进行大量重构.

It is a better way because you can use inheritance, interfaces and your method will be called on an instanciated object. This means you can define contracts and use low coupling with the classes using it. However some people consider the singleton as an anti pattern especially because if you want to have 2 or more instances of your class with different input properties (like the classic example of the connection to 2 different databases) you cannot without a big refactoring of all your code using the singleton.

服务

服务是标准类的实例.这是使代码合理化的一种方法.这种架构称为SOA(面向服务的架构).我举一个例子:

A service is an instance of a standard class. It is a way to rationalize your code. This kind of architecture is called SOA (service oriented architecture). I give you an example:

如果要添加一种方法来将商店中的产品出售给消费者,并且具有类ProductStoreConsumer.您应该在哪里实例化此方法?我可以保证,如果您认为今天在这三大类之一中比较合乎逻辑,那么明天可能还有其他事情.这导致大量重复,并且很难找到您要查找的代码.相反,您可以使用例如SaleHandler之类的服务类,该服务类将知道如何操作数据类.

If you want to add a method to sell a product in a store to a consumer and you have classes Product, Store and Consumer. Where should you instantiate this method? I can guarantee that if you think it is more logical in one of these three class today it could be anything else tomorrow. This leads to lots of duplications and a difficulty to find where is the code you are looking for. Instead, you can use a service class like a SaleHandler for example which will know how to manipulate your data classes.

使用一个可帮助您将它们相互注入的框架是一个好主意(依赖注入),以便充分利用它们.在PHP社区中,您可以在 Symfony2 例如.

It is a good idea to use a framework helping you to inject them into each others (dependency injection) in order to use them at their full potential. In the PHP community, you have a nice example of implementation of this in Symfony2 for instance.

总结:

  • 如果您没有框架,那么即使我个人更喜欢在其中进行手动依赖注入的简单文件,也可以选择单例.

  • If you do not have a framework, singletons are certainly an option even if I personally prefer a simple file where I make manual dependency injection.

如果您有一个框架,请使用其依赖项注入功能来执行此类操作.

If you have a framework, use its dependency injection feature to do that kind of thing.

您不应该使用静态方法(在OOP中).如果您在一个类中需要静态方法,则意味着您可以创建一个包含该方法的新单例/服务,并将其注入需要它的类的实例中.

You should not use static method (in OOP). If you need a static method in one of your class, this means you can create a new singleton/service containing this method and inject it to the instance of classes needing it.

这篇关于什么时候应该使用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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