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 Static Methods

Why do we need the STATIC keyword?

The code works without the keyword "static", so why do we need it?

1 Answer

Tiago Aguiar
Tiago Aguiar
10,550 Points

Declaring a method as static makes them acessible without the need of instantiate the class. Meaning: In class you can instantiate a class basically by adding the new keyword as follows:

$SomeClass = new ClassOne();

So, at the static method you can access by using either scope resolution operator or object reference operator. For instance, lets supose that the ClassOne() has an method called Foo(). In this case you can access by either $SomeClass->Foo(); OR $SomeClass::Foo();

Just remember that in PHP the static property or object are away from the object context, So you cant use the $this keyword.