开发者

difference between object and static methods

What's the difference between static and object methods开发者_开发问答? Where and why are they used differently? When do I use which one of those?


With object methods you need to instantiate the class in order to use the method so say Bark is an object method

Dog myDog = new Dog(); myDog.Bark();

But now let's say Bark was a static method. I could just do: Dog.Bark();

So a static method works on a class, not on an object.

Static methods are useful when you'd like to just make a global utility class. That way you don't need to pass an object around just to use methods on this utility class.


static methods are instantiated only once in the memory space.


Instance methods require an instance of the class to be invoked. The instance reference can be thought of as an invisible first parameter, which can be accessed within the method using the 'this' keyword in C#, C++, and Java. Static methods can be invoked without an instance of the class. They can only access instances of the class if they are passed in as parameters.

As a general rule of thumb, use an instance method when the method performs some operation on a single instance. Use a static method when the method performs an operation on multiple instances, or requires no instances.


PHP manual is very brief about that. But static is explained quite well in the book "PHP 5 Power Programming":

  • Static properties
  • Static methods
  • Singleton pattern (scroll down to the singleton section there)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜