class – What does the variable $this mean in PHP?

class – What does the variable $this mean in PHP?

Its a reference to the current object, its 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.

The best way to learn about the $this variable in PHP is to try it against the interpreter in various contexts:

print isset($this);              //true,   $this exists
print gettype($this);            //Object, $this is an object 
print is_array($this);           //false,  $this isnt an array
print get_object_vars($this);    //true,   $thiss variables are an array
print is_object($this);          //true,   $this is still an object
print get_class($this);          //YourProjectYourFileYourClass
print get_parent_class($this);   //YourBundleYourStuffYourParentClass
print gettype($this->container); //object
print_r($this);                  //delicious data dump of $this
print $this->yourvariable        //access $this variable with ->

So the $this pseudo-variable has the Current Objects methods and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:

Class Dog{
    public $my_member_variable;                             //member variable

    function normal_method_inside_Dog() {                   //member method

        //Assign data to member variable from inside the member method
        $this->my_member_variable = whatever;

        //Get data from member variable from inside the member method.
        print $this->my_member_variable;

$this is reference to a PHP Object that was created by the interpreter for you, that contains an array of variables.

If you call $this inside a normal method in a normal class, $this returns the Object (the class) to which that method belongs.

Its possible for $this to be undefined if the context has no parent Object. has a big page talking about PHP object oriented programming and how $this behaves depending on context.

class – What does the variable $this mean in PHP?

I know its old question, anyway another exact explanation about $this. $this is mainly used to refer properties of a class.


Class A
   public $myname;    //this is a member variable of this class

function callme() {
    $myname = function variable;
    $this->myname = Member variable;
    echo $myname;                  //prints function variable
    echo $this->myname;              //prints member variable


function variable

member variable

Leave a Reply

Your email address will not be published.