tags:

views:

163

answers:

5

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?

+4  A: 

It's a reference to the current object, it's most commonly used in object oriented code.

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.

meder
+1 for the terminology "the current object", as it is a more accurate way to describe the sometimes unintuitive behaviour of `$this`.
Alex Barrett
+6  A: 

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

snicker
A: 

It refers to the instance of the current class, as meder said.

See the PHP Docs. It's explained under the first example.

Marc W
+2  A: 

PHP freaks has a wonderful tutorial on Object Oriented programming.

Derleek
A: 

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
centr0