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

前端 未结 5 947
轮回少年
轮回少年 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:10

    I hope this will help clear things up:

    class Person {
    
       private $name;
       private $age;
    
       public function __construct($name, $age){
         // save func params to instance vars
         $this->name = $name;
         $this->age = $age;
       }
    
       public function say_hello(){ // look, no func params!
         echo "My name is {$this->name} and I am {$this->age} years old!";
       }
    
       public function celebrate_birthday(){ // no params again
         echo "Party time!";
         $this->age += 1; // update instance var
         $this->drink_beer();  // call instance method
       }
    
       public function drink_beer(){
         echo "Beer is good!";
       }
    }
    
    $p = new Person("Sample", "20");
    $p->say_hello();          // My name is Sample and I am 20 years old!
    $p->celebrate_birthday(); // Party time! Beer is good!
    $p->say_hello();          // My name is Sample and I am 21 years old!
    

提交回复
热议问题