What is the difference between self and this in PHP?
In PHP, “self” and “this” are both used to refer to objects, but they have different meanings and are used in different contexts.
“self” is a keyword that is used inside a class to refer to the current class. It’s used to access static properties or methods of the current class. For example:
class MyClass {
public static $myVar = 10;
public static function myMethod() {
echo self::$myVar;
}
}
MyClass::myMethod(); // Output: 10
In this example, we define a class called “MyClass” that has a static property called “$myVar” and a static method called “myMethod”. The “myMethod” method uses the “self” keyword to refer to the “MyClass” class and access its static property “$myVar”.
On the other hand, “this” is a keyword that is used inside a class method to refer to the current instance of the class. It’s used to access non-static properties or methods of the current instance. For example:
class MyClass {
public $myVar = 10;
public function myMethod() {
echo $this->myVar;
}
}
$obj = new MyClass();
$obj->myMethod(); // Output: 10
In this example, we define a class called “MyClass” that has a non-static property called “$myVar” and a method called “myMethod”. The “myMethod” method uses the “this” keyword to refer to the current instance of the class and access its non-static property “$myVar”.
In summary, “self” is used to refer to the current class and access its static properties or methods, while “this” is used to refer to the current instance of the class and access its non-static properties or methods.