I am using \'this\' keyword for a long time. But when someone asks me to explain it, I am confused that how to explain it. I know that I can use this in a method of class to
Like their name suggests, instance methods operate on instances of a class. How do they know which one to operate on? That's what the this
parameter is for.
When you invoke an instance method, you're really invisibly passing in an extra parameter: the object to invoke it on. For example, when you have this:
class Basket {
public function a() {
$this-> ...;
// ...
}
// ...
}
and you call $some_basket->a()
, behind the scenes you're actually calling something like Basket::a($some_basket)
. Now a()
knows which Basket
you want to work with. That special parameter is what this
refers to: the current object you're dealing with.