开发者

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

开发者 https://www.devze.com 2022-12-19 11:38 出处:网络
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?$this is a reserved variable name

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?


$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


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


This question just popped up after an update. I liked the question, so I thought I'd add my own example of the difference.

class Test
{
    public $bar = 'bar';
    public $foo = 'foo';

    public function __construct()
    {
        $bar = 'foo';

        $this->bar; // bar
        $this->$bar; // foo
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号