How does $this-> differ from self:: in PHP object-oriented programming?
$this-> refers to an instance variable or method within an object, while self:: refers to a static variable or method within a class. When using $this->, you are accessing the specific instance of the object's property or method, while self:: accesses the class itself. It's important to use $this-> when working with instance-specific data and self:: when working with class-wide data.
class Example {
public $instanceVariable = 'Instance variable';
public static $staticVariable = 'Static variable';
public function getInstanceVariable() {
return $this->instanceVariable;
}
public static function getStaticVariable() {
return self::$staticVariable;
}
}
$example = new Example();
echo $example->getInstanceVariable(); // Output: Instance variable
echo Example::getStaticVariable(); // Output: Static variable