Can you define a static method outside of a class?

2.5k views Asked by At

Let's say I have a class:

class test {
    public static function sayHi() {
        echo 'hi';
    }
}

Call it by test::sayHi();

Can I define sayHi() outside of the class or perhaps get rid of the class altogether?

public static function sayHi() {
      echo 'hi';
}

I only need this function to encapsulate code for a script. Maybe the answer is not a static method but a plain function def?

2

There are 2 answers

3
Markus Müller On BEST ANSWER

A static method without a class does not make any sense at all. The static keywords signals that this method is identical for all instances of the class. This enables you to call it.. well.. statically on the class itself instead of on one of its instances.

If the content of the method is self-contained, meaning it does not need any other static variables or methods of the class, you can simply omit the class and put the code in a global method. Using global methods is considered a bad practice.

So my advice is to just keep the class, even if it has only that one method within. This way you can still autoload the file instead of having to require it yourself.

0
Asfo On

Functions in OOP are public by default, you can modify them to private like:

private function test(){
    //do something
}

Or like you said, to static, in public or private like:

private static function test(){
   //do something
}

But if you're not using OOP, functions by default are global and public, you can't change their access to private. That's not the way they are supposed to works because if you change their type to private, you will NEVER be able to access to that function. Also, static doesn't works because is another property of OOP...

Then, you can simply create that function and access it from everywhere you want (obviously where is available :P because you need to include the file where is stored)