Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHenrique Zafniksi
8,560 PointsUsability of a static property/method?
From what I've read, static properties/methods are accessible without need to instantiate. How is that better in a real situation?
See, I do understand why extended classes can have different attributes such as colors for shirts, and flavor for sodas, but why would all of those different classes share an unique static property with a single value for all?
Could you give examples of what cases using "public static $property" is better than "public $property"?
1 Answer
William LaMorie
11,769 PointsFrom what I understand, a lot of times when people use static methods and classes, it's really just a strict adherence to the OOP paradigm.
For example, an often given example of 'why use static' is the Math class in Java, where all the constants of the class static properties. Of course, you wouldn't want to have to make a new Math object when you wanted to use a constant, so of course you'd want it static....
The less non-trivial counterargument to that being... well, do I really want to encapsulate these values in a class in the first place if my language of choice doesn't require me to? This ties you to the class, and gets dicey when you start looking at using polymorphism to swap classes out and stuff, or so I've come to read.
However, there are times when they seem to be very much useful, the big example that I've had presented to me learning PHP from a variety of sources is using the Singleton pattern of object instantiation in user logins. There's a wiki piece about Singletons here: http://en.wikipedia.org/wiki/Singleton_pattern
Actually, one of the sites I had bookmarked from when I looked into same thing seems to have a pretty good (Java oriented) discussion of this whole thing here (actually it seems to have ended being the primary thing that has informed me on the topic, looking at it some more): http://www.coderanch.com/t/407852/java/java/static-methods
Henrique Zafniksi
8,560 PointsHenrique Zafniksi
8,560 PointsVery elaborated and conclusive answer. Thank you!