When to use $this->property instead of $property in PHP

前端 未结 5 948
轮回少年
轮回少年 2020-12-18 09:32

Super easy question. Look at the 2 sample class methods.

In the first One I pass in a variable/property call $params I then do $this->params

5条回答
  •  没有蜡笔的小新
    2020-12-18 10:06

    In general you can use specific variable when they're in the context ("scope") of your object.

    In OOP programming, $this will almost always be used to access a class variable or other class method.

    class MyClass{
         private $myNum;
    
         public function myFunc(){
              echo 'My number is '.$this->myNum; // Outputting the class variable "myNum"
         }
    
         public function go($myNumber){
              $this->myNum  = $myNumber; // Will set the class variable "$myNum" to the value of "$myNumbe" - a parameter fo the "go" function.
              $this->myFunc(); // Will call the function "myFunc()" on the current object
         }
    }
    

    Shai.

提交回复
热议问题