When would you use the $this keyword in PHP?

前端 未结 12 1727
长发绾君心
长发绾君心 2020-12-15 11:03

When would you use the $this keyword in PHP? From what I understand $this refers to the object created without knowing the objects name.

Al

12条回答
  •  离开以前
    2020-12-15 11:31

    The most common use case is within Object Oriented Programming, while defining or working within a class. For example:

    class Horse {
        var $running = false;
    
        function run() {
            $this->running = true;
        }
    }
    

    As you can see, within the run function, we can use the $this variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this variable inside of each one will refer to that specific instance of the Horse class, not to them both.

提交回复
热议问题