Home » Php » PHP | Why should I use public static / private static function instead of public / private function?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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 ?

How to&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();