user1085195
user1085195

Reputation: 395

Declaring functions as static in php

I have a set of independent functions which I want to put in a class. They do not depend on any objects of the class, so while calling them, all the values required would be passed as arguments. Is it fine if I declare all of them as static so that i can call them with just one command like className::functionName(argument1,argument2,...) or do i keep them as normal public function and call them through a class object?

Upvotes: 0

Views: 88

Answers (2)

tuxtimo
tuxtimo

Reputation: 2790

Yes this is not bad. You can define them as static functions and like you said - you can call them with just one statement.

class Foo {
   public static function bar( ) {
      echo "bar called";
   }
}

Upvotes: 0

PeeHaa
PeeHaa

Reputation: 72652

You can (but you shouldn't do it):

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

YourClass::yourMethod();

The reason why you shouldn't do it is because when you use the static call in some other class / function / whatever you have tightly coupled the YourClass to the other class. hence you are making it pretty hard to do unit tests or simply switch to another moethod without going trhough all the code where it is used. And also don't forget you just added something globally.

You also say:

I have a set of independent functions which I want to put in a class.

This is a big code smell in my book. This makes it sound like your class violates the SRP principle in SOLID programming.

Hence I would just instantiate the class.

Let's see why it makes your code hard to test:

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
    }
}

Also that that SomeClassWithMethods::doSomething is now globally defined.

We like to call this the silver bullet :) :

super::$static silver bullet

Upvotes: 5

Related Questions