Using this inside a static function fails

I have this method that I want to use $ this in, but all I get is: Fatal error: using $ this, if not in the context of the object.

How can I make this work?

public static function userNameAvailibility() { $result = $this->getsomthin(); } 
+64
oop php this static-methods
Feb 18 '10 at 6:18
source share
6 answers

This is the right way.

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

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

See: PHP Static Method Tutorial for more information :)

+117
Feb 18 '10 at 6:24
source share

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

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

+13
Feb 18 '10 at 6:22
source share

The this accessor refers to the current instance of the class. Since static methods do not start from an instance, using this prohibited. Therefore, you must immediately call the method. The static method cannot access anything in the scope of the instance, but gain access to everything in the scope of the class outside the scope of the instance.

+2
Feb 18 2018-10-18T00
source share

In a static function, you can call only static functions using self :: if your class contains a non-stationary function that you want to use, you can declare an 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(); } } ?> 
+2
01 Oct '13 at
source share

Here is an example of what happens when a class method is called in the wrong way. You will see some warnings when this code is executed, but it will work and print: "I A: print property B". (Done in php5.6)

 class A { public function aMethod() { echo "I'm A: "; echo "printing " . $this->property; } } class B { public $property = "B property"; public function bMethod() { A::aMethod(); } } $b = new B(); $b->bMethod(); 

This means that the variable $ this, used in a method that is called as a static method, points to an instance of the calling class. In the above example, there is a $ this-> property used in class A that points to property B.

+1
May 17 '17 at 8:28
source share

Too bad PHP doesn't show a sufficiently descriptive error. You cannot use $ this-> inside a static function, but rather use self :: if you need to call a function inside one class

0
Feb 16 '17 at 13:26
source share



All Articles