Using $this inside a static function fails

76,508

Solution 1

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 :)

Solution 2

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.

Solution 3

Only static functions can be called within the static function using self:: if your class contains non static function which you want to use then you can declare the instance of the same class and use it.

<?php
class some_class{
function nonStatic() {
    //.....  Some code ....   
    }
 Static function isStatic(){
    $someClassObject = new some_class;
    $someClassObject->nonStatic();
    } 
}
?>

Solution 4

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.

Solution 5

In the static method,properties are for the class, not the object. This is why access to static methods or features is possible without creating an object. $this refers to an object made of a class, but $self only refers to the same class.

Share:
76,508
Jom
Author by

Jom

Updated on May 14, 2020

Comments

  • Jom
    Jom about 4 years

    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();
    }
    
  • Gaurav Sharma
    Gaurav Sharma about 14 years
    true, I was about to post this answer.
  • Jom
    Jom about 14 years
    There should be when you are trying to assign the static variable to an instance variable. Is this not possibel?
  • thorinkor
    thorinkor almost 11 years
    You should also remember, that the getsomthin() method has to be static too - You can't call non-static inside a static method.
  • Pacerier
    Pacerier almost 11 years
    @Sarfraz, shouldn't it be static:: instead of self::?
  • thnkwthprtls
    thnkwthprtls over 10 years
    Is there any way to do something similar to this in C/C++?
  • xavier bs
    xavier bs over 3 years
    self::staticMethod() or $self = new self(); and $self->nonStaticMethod();
  • Jenuel Ganawed
    Jenuel Ganawed almost 2 years
    how about the variable