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

后端 未结 7 1292
不思量自难忘°
不思量自难忘° 2020-12-17 09:38

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

Example:

I\'ve seen this code recently.

7条回答
  •  星月不相逢
    2020-12-17 10:01

    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.

      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
      

提交回复
热议问题