Junior — Middle
Can you explain the differences between the keywords self and this in programming?
sobes.tech AI
Answer from AI
In PHP, the keywords self and this are used to refer to class elements but have different contexts:
-
thisis a reference to the current object instance. It is used inside object methods to access its properties and methods. -
selfis a reference to the class itself, used to access static properties and methods within the class.
Example:
class Example {
public $instanceVar = 'instance';
public static $staticVar = 'static';
public function instanceMethod() {
echo $this->instanceVar; // access to object property
}
public static function staticMethod() {
echo self::$staticVar; // access to static class property
}
}
$obj = new Example();
$obj->instanceMethod(); // outputs 'instance'
Example::staticMethod(); // outputs 'static'
Thus, this is used for working with a specific object, while self is used for working with the class as a whole.