What is $this keyword meant for?

14,181

Solution 1

$this refers to the current object

Manual says:

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

Little example:

class Test
{
    private $var;

    public function func()
    {
        $this->var = 1;
        return $this->var;
    }
}

$obj = new Test();

$obj->func();

Solution 2

$this is reference to current object while inside that objects code.

You'll find more information in PHP OOP basics.

Solution 3

So, simply :

  • $this refers to current object instance
  • -> indicates that the part on the right is a method of an object

In other words :

$this->doSth() means : run method doSth of the same object.

Solution 4

$this hold the reference of the selected object in use, -> is an operator used to assign a method or property to an object reference.

Solution 5

I think this page say's it all: http://php.net/manual/en/language.oop5.basic.php

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

in few words it's the calling object.

Share:
14,181
Developing Developer
Author by

Developing Developer

Updated on June 08, 2022

Comments

  • Developing Developer
    Developing Developer almost 2 years

    Please explain me that for what $this and -> stands for...lets take the example of following code...

    $this->convertNamesToCaptions($order, $formId)