Where's the difference between self and $this-> in a PHP class or PHP method?

$this refers to the instance of the class, that is correct. However, there is also something called static state, which is the same for all instances of that class. self:: is the accessor for those attributes and functions.

Also, you cannot normally access an instance member from a static method. Meaning, you cannot do

static function something($x) {
  $this->that = $x;
}

because the static method would not know which instance you are referring to.


$this refers to the current object, self refers to the current class. The class is the blueprint of the object. So you define a class, but you construct objects.

So in other words, use self for static and this for non-static members or methods.


  1. this-> can't access static method or static attribute , we use self to access them.
  2. $this-> when dealing with extended class will refer to the current scope that u extended , self will always refer to the parent class because its doesn't need instance to access class method or attr its access the class directly.

    <?php
    class FirstClass{
      function selfTest(){
        $this->classCheck();
        self::classCheck();
      } 
      function classCheck(){
        echo "First Class";
      }
    }
    class SecondClass extends FirstClass{
        function classCheck(){
          echo "Second Class";
        }
    }
    $var = new SecondClass();
    $var->selfTest(); //this-> will refer to Second Class , where self refer to the parent class
    

Tags:

Php

Oop

This