Home » Php » design patterns – Besides singletons, what are some compelling reasons to use static methods in PHP?

design patterns – Besides singletons, what are some compelling reasons to use static methods in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I recently answered this question:

What are good reasons to use static methods in PHP?

The first thing to come to mind, of course, was a singleton. With little exception, the other answerers provided the same singleton example. But that got me thinking… I don’t really ever use static methods or properties for anything besides creating singletons!

A brief search netted many tutorials on using static methods, almost all of which implement some variation of the same singleton class.

I’m really interested: What reason do we have to make static methods other than creating singletons (or other than just being lazy and wanting a global function)?

Does anyone have a pragmatic example of using a static method that could not be accomplished better using a dynamic design pattern? The example can be a singleton if that makes sense in it’s context, but I’m interested in other reasons besides the singleton-aspect of the solution.

How to&Answers:

A factory pattern will normally use a static call as well; but it’s sensible to use static methods for any class mathod that has no dependencies on the instance properties or other instance methods, especially when they’re called regularly, for performance reasons.

The logical place for the following method in PHPExcel is in the PHPExcel_Cell class, because it pertains directly to manipulating a cell address (any cell address, not just the address of a specific instance), but it has no dependency on the instance, so I declare it static.

public static function stringFromColumnIndex($pColumnIndex = 0) {
    if ($pColumnIndex < 26) {
        return chr(65 + $pColumnIndex);
    } elseif ($pColumnIndex < 702) {
        return chr(64 + ($pColumnIndex / 26)).chr(65 + $pColumnIndex % 26);
    }
    return chr(64 + (($pColumnIndex - 26) / 676)).chr(65 + ((($pColumnIndex - 26) % 676) / 26)).chr(65 + $pColumnIndex % 26);
}

And this method isn’t particularly difficult to test

Answer:

It’s not necessarily about patterns. PHP is not a persistent environment, so lifetime of any object instance is likely to be milliseconds, but it requires memory allocation/release and extra cpu cycles. Unless you need reusable objects or collections, I find non-static objects to have little justification.

Answer:

Tongue in cheek answer, there aren’t any. Static methods are very very hard to test or mock.