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, and the search engines ignore the $
and I end up with a search for the word "this".
Can someone tell me how the variable $this works in PHP?
It refers to the instance of the current class, as meder said.
See the PHP Docs. It's explained under the first example.
The best way to learn about the
$this
variable in php is to ask PHP what it is. Don't ask us, ask the compiler: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:
I know its old question, anyway another exact explanation about $this. $this is mainly used to refer properties of a class.
Example:
output:
It is the way to reference an instance of a class from within itself, the same as many other object oriented languages.
From the PHP docs:
$this is a special variable and it refers to the same object ie. itself.
it actually refer instance of current class
here is an example which will clear the above statement