I was just wondering what are the advantages of using a public static function
or private static function
instead of simply public function
or private function
?
They are a utility One of the reasons you should use private static methods is to reduce the complexity of the code. For instance, if there are multiple public methods in your code, there are multiple ways the program can manipulate the objects. Hence, error correction and debugging become extremely difficult.
A static private method provides a way to hide static code from outside the class. This can be useful if several different methods (static or not) need to use it, i.e. code-reuse.
Yes, we can have private methods or private static methods in an interface in Java 9. We can use these methods to remove the code redundancy. Private methods can be useful or accessible only within that interface only. We can't access or inherit private methods from one interface to another interface or class.
private or public doesn't make a difference - static methods are OK, but if you find you're using them all the time (and of course instance methods that don't access any instance fields are basically static methods for this purpose), then you probably need to rethink the design.
"Normal" methods (usually called instance methods) are invoked on an instance of the class in which they're defined. The method will always have access to its object via $this
, and so it can work with data carried by that object (and indeed modify it). This is a core aspect of object oriented programming, and it's what makes a class more than just a bunch of data.
Calls to static methods, on the other hand, aren't associated with a particular object. They behave just like regular functions in this respect; indeed the only difference is that they may be marked private
and also have access to private methods and variables on instances of own their class. Static functions are really just an extension of procedural programming.
For example, an instance method is called on an object:
$object = new MyClass();
$result = $object->myInstanceMethod();
A static method is called on the class itself:
$result = MyClass::myStaticMethod();
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