Home  >  Q&A  >  body text

Static functions cannot use $this

I have this method and I want to use $this in it, but all I get is: Fatal error: $this is not used in an object context.

How can I make it work?

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


P粉277464743P粉277464743389 days ago572

reply all(2)I'll reply

  • P粉810050669

    P粉8100506692023-10-18 12:20:45

    You cannot use $this inside a static function because static functions are independent of any instantiated object. Try to make the function not static.

    edit: By definition, static methods can be called without any instantiated object, so using $this in a static method doesn't make any sense.

    reply
    0
  • P粉633075725

    P粉6330757252023-10-18 10:24:37

    This is the right thing to do

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

    For static methods , use self:: instead of $this->.

    See: PHP Static Method TutorialMore information:)

    reply
    0
  • Cancelreply