$this vs self in PHP

$this refers to the current object of the class and self refers to the current class itself.
$this can not be used inside static function whereas self can be used inside static function.

When we need to access static function and reference static member variable then we can’t access through $this because a property declared as static cannot be accessed with an instantiated class object.

In below example , I explain how we can access a variable using regularMethod and staticMethod. To access static properties or method we don’t need to create object of the class. We can access it using class name scope resolution operator (::) and property or method name ( e.g fooBar::$staticVar, fooBar::staticMethod() )

$this vs self example in PHP:

<?php
class fooBar
{
   public $var;
   public static $staticVar;

   public function regularMethod() {
      echo $this->var;
   }
   /**
   * Demonstration: static method and usages of static variable.
   */
   public static function staticMethod() {
      echo self::$staticVar;
     // echo $this->staticVar;
     //  If you are try to use $this here you will get
     //  Fatal error: Using $this when not in object context....
   }
}

/**
* Declaring class properties or methods as static makes them accessible
* without needing an instantiation of the class.
* AS we set $staticVar variable value without creating object of fooBar class
*/
fooBar::$staticVar = "Static Variable Value , Called by staticMethod";
$obj = new fooBar();
$obj->var = "Regular Variable, called by regularMethod";
// static methods are callable without an instance of the object created
echo fooBar::staticMethod(); // Output : Static Variable Value , Called by staticMethod
echo $obj->regularMethod(); // Output //
?>
(Visited 107 times, 8 visits today)