Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 when not in object context.

How can I get this to work?

public static function userNameAvailibility() {      $result = $this->getsomthin(); } 
like image 700
Jom Avatar asked Feb 18 '10 06:02

Jom


People also ask

Can we use $this variable in static method?

Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.

Why we can't use this inside static methods?

No, we can't use “this” keyword inside a static method. “this” refers to current instance of the class. But if we define a method as static , class instance will not have access to it, only CLR executes that block of code. Hence we can't use “this” keyword inside static method.

How use $this in static method in PHP?

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.

Can we use super keyword in static method?

Where the "super" keyword in Java is used as a reference to the object of the superclass. This implies that to use "super" the method should be invoked by an object, which static methods are not. Therefore, you cannot use the "super" keyword from a static method.


1 Answers

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

like image 199
Sarfraz Avatar answered Sep 28 '22 06:09

Sarfraz