Is using an instance of a class to access static methods considered bad practice?
I.e.
$model = new MyClass();
$options = MyClass::getOptions();
vs
$model = new MyClass();
$options = $model::getOptions();
($model
is instantiated in either case, I'm just wondering if one approach is preferable to the other.)
Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.
Instance method vs Static method Static methods can access the static variables and static methods directly. Static methods can't access instance methods and instance variables directly. They must use reference to object.
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
Static methods are common to most object-oriented programming languages, including Java. What differentiates static from instance methods is that they have no object that owns them. Instead, static methods are defined on the class level and can be used without creating instances.
Traditionally the first way (specifying the class name itself) has more similarities with other languages such as Java.
The second one is unique to PHP (afaik); it works because the ::
operator disambiguates the expression, unlike Java where a period is used for both instance and static properties.
I'm not sure what the performance impact is by using the second option, but I think it comes down to personal taste / coding standards.
Conclusion
If the types of your instances are immediately clear from the surrounding code it might be easier to go for the second option (sometimes the class name can be pretty big); but if not, use the first option as it's the most explicit.
That depends, I think. You can happily use static methods for many happy years, enjoying instantiation-free code, but one day you'll have to reroute some (that's where it goes) calls to another, descendant class, so simple search-and-replace call won't do. ) So going with a prepared object is a safer route, I think.
As an alternative, you can use something like this:
$className = 'MyClass';
$className::classyMethod1();
$className::classyMethod2();
... but that may become pretty confusing with time, I suppose (and is usable only in PHP 5.3+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With