7

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 ?

5
  • This is not a question of advantage or disadvantage. Also, have you searched the site?
    – BoltClock
    Commented Jan 9, 2012 at 7:09
  • 4
    you don't need to create object to use static methods..And there's a lot of related questions!
    – meze
    Commented Jan 9, 2012 at 7:09
  • Yes, I was reading some from PHP Manual site, but I don't seem to understand why useing static methods, I only understood that instead of calling the public function like this -> I can do this :: and some other info I read about static methods on php manual site ...
    – Roland
    Commented Jan 9, 2012 at 7:13
  • @Roland This question is more related to the object-oriented paradigm in itself than to a specific language. Therefore, you might be better off reading through a introduction to static methods in general.
    – jensgram
    Commented Jan 9, 2012 at 13:01
  • 1
    Even though this is closed, it's the first thing I found whilst googling to answer my question as to what the difference is between static and non-static class functions in PHP. Thanks @meze Commented Oct 15, 2012 at 15:58

1 Answer 1

22

"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();

Not the answer you're looking for? Browse other questions tagged or ask your own question.