0

What I think I know so far:

so $this-> is to access a function/var outside its own function/var ?

but how does $this-> know if its a function or a variable ?

why we refer to a var like this $this->data instead of this $this->$data ?

hakre
  • 193,403
  • 52
  • 435
  • 836
NSanjay
  • 221
  • 1
  • 6
  • 13
  • "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). " http://www.php.net/manual/en/language.oop5.basic.php –  Mar 07 '11 at 02:52
  • I wonder if such question has been never asked here on SO. – zerkms Mar 07 '11 at 02:53
  • possible duplicate of [PHP: self vs. $this](http://stackoverflow.com/questions/151969/php-self-vs-this) – Gordon Mar 07 '11 at 08:23

4 Answers4

7

$this refers to the current object that a method has been invoked on. It knows if it's a function if there is a pair of parentheses at the end. We use the former syntax because $this->$data means look at the field whose name is $data; e.g. $this->foo if $data == 'foo'

Edward Z. Yang
  • 26,325
  • 16
  • 80
  • 110
3

$this is the variable referring to the object that you are currently inside. $this-> will access either a method or field in the current object.

As for why is it $this->data and not $this->$data, that's just a syntax quirk. You'd have to ask the PHP language designers. It's probably because the latter wouldn't make much sense for a method.

If this looks like Greek to you, then you may want to head over to the PHP manual's section on classes and objects and read up.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
1

$this represents the instance of a given object, from the context of within the object.

I would say, knowing whether you're accessing a method or property is your responsibility. Read documentation. If you're calling an object method using this, it uses the expected syntax of $this->method($args); and properties (member variables) use the expected syntax of $this->var = 'value';

Dan Lugg
  • 20,192
  • 19
  • 110
  • 174
0

It's a pretty long subject, but in sort, $this is a pointer to an instance. $this->data refers to the data variable of a particular instance(this instance). It is $this->data and not $this->$data just because of convention.

Spyros
  • 46,820
  • 25
  • 86
  • 129