NSanjay
NSanjay

Reputation: 211

What is $this->?

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 ?

Upvotes: 0

Views: 326

Answers (4)

Dan Lugg
Dan Lugg

Reputation: 20612

$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';

Upvotes: 1

Spyros
Spyros

Reputation: 48676

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.

Upvotes: 0

Edward Z. Yang
Edward Z. Yang

Reputation: 26742

$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'

Upvotes: 7

Rafe Kettler
Rafe Kettler

Reputation: 76965

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

Upvotes: 3

Related Questions