Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Object-Oriented PHP Basics (Retired) Inheritance, Interfaces, and Exceptions Static Methods and Properties

Henrique Zafniksi
Henrique Zafniksi
8,560 Points

Usability 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
William LaMorie
11,769 Points

From 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
Henrique Zafniksi
8,560 Points

Very elaborated and conclusive answer. Thank you!