views:

152

answers:

3

I have this method that I want to use $this in but all I get is: Fatal error: Using $this when not in object context.

How can I get this to work?

public static function userNameAvailibility()
{
     $result = $this->getsomthin();
}
+2  A: 

You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static.

Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.

catchmeifyoutry
There should be when you are trying to assign the static variable to an instance variable. Is this not possibel?
Jom
A: 

The accessor this refers to the current instance of the class. As static methods does not run off the instance, using this is barred. So one need to call the method directly here. The static method can not access anything in the scope of the instance, but access everything in the class scope outside instance scope.

Kangkan
+6  A: 

This is the correct way

public static function userNameAvailibility()
{
     $result = self::getsomthin();
}

Use self:: instead of $this-> for static methods.

See: PHP Static Methods Tutorial for more info :)

Sarfraz
true, I was about to post this answer.
Gaurav Sharma