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". Not exactly what I wanted. So, can anyone tell me?
It's a reference to the current object, it's most commonly used in object oriented code.
- Reference: http://www.php.net/manual/en/language.oop5.basic.php
- Primer: http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html
Example:
<?php
class Person {
public $name;
function __construct( $name ) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
This stores the 'Jack' string as a property of the object created.
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:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
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