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
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.