Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `$this->name` and `$this->$name`?

Tags:

php

class

I am wondering what is the difference between $this->name and $this->$name? Also does $this have to be strictly named this or can it be anything?

like image 382
Strawberry Avatar asked Feb 05 '10 05:02

Strawberry


2 Answers

$this is a reserved variable name and can not be used for anything else. It specifically points you to the object your are currently working in. You have to use $this because you do not know what variable object will be assigned to.

$this->name refers to the current class's variable name

$this->$name refers to the class variable of whatever the value of $name is. Thus

$name = "name";
echo $this->$name; // echos the value of $this->name.

$name = "test";
echo $this->$name;  // echos the value of $this->test
like image 173
Tyler Carter Avatar answered Sep 17 '22 13:09

Tyler Carter


$this is a reserved name used in PHP to point to the current instance of the class you are using it in (quoting) :

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


When using $this->name, you are accessing the property with the name name of the current object.


When using $this->$name, $name is determined before accessing the property -- which means you'll access the property which name is contained in the $name local variable.

For instance, with this portion of code :

$name = 'abc';
echo $this->$name;

You'll actually echo the content of the abc property, as if you had written :

echo $this->abc;

When doing this, you are using variable variables (quoting) :

Class properties may also be accessed using variable property names.
The variable property name will be resolved within the scope from which the call is made.
For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo.
This is also true if $bar is an array access.

like image 41
Pascal MARTIN Avatar answered Sep 18 '22 13:09

Pascal MARTIN