What does the variable $this mean in PHP?

前端 未结 10 1770

I see the variable $this in PHP all the time and I have no idea what it\'s used for. I\'ve never personally used it.

Can someone tell me how the variab

10条回答
  •  独厮守ぢ
    2020-11-22 05:50

    when you create a class you have (in many cases) instance variables and methods (aka. functions). $this accesses those instance variables so that your functions can take those variables and do what they need to do whatever you want with them.

    another version of meder's example:

    class Person {
    
        protected $name;  //can't be accessed from outside the class
    
        public function __construct($name) {
            $this->name = $name;
        }
    
        public function getName() {
            return $this->name;
        }
    }
    // this line creates an instance of the class Person setting "Jack" as $name.  
    // __construct() gets executed when you declare it within the class.
    $jack = new Person("Jack"); 
    
    echo $jack->getName();
    
    Output:
    
    Jack
    

提交回复
热议问题