0

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?

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

can u please be clearer about the reason why I shouldn't do it
@user1085195 He was pretty clear. It introduces tightly coupled code which violates the single responsibility principle.
SomeClassYouWantToTest depends on SomeClassWithMethods while it does not tell anyone. That dependency is hidden behind, it can not be changed nor is it properly documented. PHP has not in-class-contextual-name-resolution, so this is fixed. It must not be bad, but if you do that in serial style across multiple layers / processings of your application you should be honest enough to admit: Let's do procedural programmer and do that right and I know what I do. Most often the sad story is that most don't know the one or either so they mix up everything and that becomes really akward to maintain
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.