Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP | Why should I use public static / private static function instead of public / private function? [closed]

Tags:

php

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 ?

like image 383
Roland Avatar asked Jan 09 '12 07:01

Roland


People also ask

Should static methods be private or public?

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.

What is the point of a private static function?

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.

Does it make sense to have private static method?

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.

Should static methods always be public?

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.


1 Answers

"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();
like image 158
Will Vousden Avatar answered Oct 06 '22 17:10

Will Vousden