What does the variable $this mean in PHP?


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?

12/11/2013 4:58:56 PM

Accepted Answer

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


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.

10/6/2009 5:33:30 AM

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:

print gettype($this);            //object
print get_object_vars($this);    //Array
print is_array($this);           //false
print is_object($this);          //true
print_r($this);                  //dump of the objects inside it
print count($this);              //true
print get_class($this);          //YourProject\YourFile\YourClass
print isset($this);              //true
print get_parent_class($this);   //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow