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 (Retired) Inheritance, Interfaces, and Exceptions Static Methods and Properties

Confused about why you should use static properties/methods? See if this helps.

I think this video ends up being really confusing about the benefits of using static properties or methods, because it uses an example in which there are already objects of the class.

In the example used by Hampton, we could have just created a (non-static) public variable $manufacturer, like this:

public $manufacturer = "Bart Taylor";

and then access it normally in the getMaker() method; like this:

public function getMaker(){ return $this->manufacturer; }

As the getMaker() method is being called relative to the $shirt object, this would work just fine, and you could echo the value of the $manufacturer property like this:

echo $shirt->manufacturer;

or like this:

echo $shirt->getMaker();

There would have been no need to add the static keyword at all.

As I take it from reading the Static Keyword Docs, the main benefit of using static properties/objects is that you can access their values even without any objects having been created, ie, directly from the class.

So if you had a class Foo with a static property and a static method, like this:

class Foo { public static $color = "Blue";

public static function description() { echo "Foo is a " . self::$color . " square.<br>"; } }

You could access them directly from the class (without any object), like this:

Foo::description();

echo Foo::$color;

As the example being detailed here works with objects, this ends up being lost in translation, and the result, I think, is a very confusing and frustrating lesson.

PS: if there's something you think I missed or didn't get right, please add a comment and let me know, ok?