在php中将函数声明为static

use*_*195 0 php static-methods

我有一组独立的函数,我想把它放在一个类中.它们不依赖于类的任何对象,因此在调用它们时,所需的所有值都将作为参数传递.如果我将它们全部声明为静态以便我可以只使用一个命令来调用它们,className::functionName(argument1,argument2,...) 或者我将它们保存为普通的公共函数并通过类对象调用它们,这样可以吗?

Pee*_*Haa 5

你可以(但你不应该这样做):

class YourClass {
   public static function yourMethod( ) {
      echo "method called";
   }
}

YourClass::yourMethod();
Run Code Online (Sandbox Code Playgroud)

你不应该这样做的原因是因为当你在其他类/函数中使用静态调用时,无论你将YourClass其与其他类紧密耦合.因此,你很难进行单元测试,或者只是切换到另一个方法,而无需使用所有使用它的代码.而且也不要忘记你只是添加了一些东西global.

你还说:

我有一组独立的函数,我想把它放在一个类中.

这是我书中的一大代码味道.这使得它听起来像你的类违反了SRP原则,扎实的编程.

因此,我只是实例化该类.

让我们看看为什么它会让您的代码难以测试:

class SomeClassWithMethods
{
    public static function doSomething()
    {
    }
}

class SomeClassYouWantToTest
{
    public function doSomething()
    {
        return SomeClassWithMethods::doSomething(); // this is now tightly coupled and would be impossible to mock when unit testing it
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,SomeClassWithMethods::doSomething现在全球定义.

我们喜欢称之为银弹:):

super :: $ static silver bullet