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 trial

PHP Object-Oriented PHP Basics Building the Recipe Recipe Details

why would I use a static method to print something?

I can use a simple method to print something, i.e.

class Work { public function displaySomething() { $output = "print this"; return $output; } }

Why would I create another class with a static method to do the same?

3 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Tori Tech S.A.C. ! The big benefit to having a static function is that you don't first need an instance of that class to use it. Imagine for a moment that we operate a veterinary clinic. And for some reason, we want to be able to print the Latin names of the animals. So for every rabbit that checks in, I create an instance of Rabbit. So $fluffy = new Rabbit("Fluffy");. The scenario here presumes the constructor takes a name and this rabbit's name is "Fluffy". Hang in there with me. If it's not a static method then I can only call it on an instance. So I could do $fluffy->printLatin().

But what happens if I just want to print the Latin name for rabbit but don't currently have a rabbit patient? The answer would be a static method that prints the Latin name for Rabbit directly from the class. Then I could do Rabbit::printLatin().

Hope this helps! :sparkles:

OK but with both I get the same result. I wonder if there is an improvement in performance if I use static? So far it sounds/seems that statics are way better if I simply want to use a method w/o storing any data but just do an action?

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Tori Tech S.A.C. Essentially, yes. There may be times when you don't need an instance of an object but still want to do something that is related to that class as opposed to tightly coupled with an instance of that class :smiley:

This will become a bit more obvious the first time you encounter a use case for it.

Thanks!