-2

What is the use of $this keyword? Output for both cases are same then why should we need to use $this keyword. And where $this keyword is used .

<?php
 class Test
 {
  private $var;
  public function func1()
   {
    $this->var = 1;     
    return $this->var;
   }
  public function func2()
  {
    $var = 2;       
    return $var;
  }
}

$obj = new Test();

echo $obj->func1();
echo $obj ->func2();

?>

Output for both cases 12 and 12.

  • 1
    $this refers to the current object – Ankur Tiwari Apr 29 '16 at 07:23
  • 5
    [Essential reading](http://php.net/manual/en/language.oop5.php) – Mark Baker Apr 29 '16 at 07:25
  • Possible duplicate of [What is $this keyword meant for?](http://stackoverflow.com/questions/9974804/what-is-this-keyword-meant-for) or [How to explain 'this' keyword in a best and simple way?](http://stackoverflow.com/questions/2094052/how-to-explain-this-keyword-in-a-best-and-simple-way) – Ani Menon Apr 29 '16 at 08:27
  • In your method `func2()`, `$var` is locally scoped, so it only exists inside `func2()` and can't be accessed by any other methods in your class. In method `func1()` you're referencing the class property `$var` by using `$this->var`.... class properties are available to any method in the class – Mark Baker Apr 29 '16 at 10:31

3 Answers3

1

$this refers to the current objec

$this->var = 1;

the $object->var value has changed to 1.


$var = 2;

the $object->var not changed.

 class Test
 {
  public $var = 0;
  public function func1()
   {
    $this->var = 1;     
    return $this->var;
   }
  public function func2()
  {
    $var = 2;       
    return $var;
  }
}

$obj = new Test();

echo "By default $obj->var is : ".$obj->var;
$obj->func1();
echo "<hr />By func1 $obj->var change to : ".$obj->var;
$obj->func2();
echo "<hr />By func2 $obj->var still is : ".$obj->var;
exit;

The output

By default $obj->var is : 0
By func1 $obj->var change to : 1
By func2 $obj->var still is : 1
suibber
  • 267
  • 1
  • 6
0

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

it is actually refering instance of current class.

Nishant Singh
  • 3,055
  • 11
  • 36
  • 74
  • Within a function always it will refer to current obj. Are you saying global variable vs local variable. – AskmeBunty Apr 29 '16 at 07:27
  • yes, its usually the object to which the method belongs, but possibly another object only if the method is called staticaly from the context of a secondary object – Nishant Singh Apr 29 '16 at 07:29
0

In very general terms, we can say that $this is used to reference the current object, you can got a good explanation here What is $this keyword meant for? or How to explain 'this' keyword in a best and simple way?

Community
  • 1
  • 1
Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40