PHP代码:此关键字的用法

时间:2010-12-14 09:27:32

标签: php

public function __construct($template = '', array $data = array())
{
    if ($template !== '') {
        $this->setTemplate($template);
    }
    if (!empty($data)) {
        foreach ($data as $name => $value) {
            $this->$name = $value;
        }
    }
}

从破解的复合视图教程(http://www.devshed.com/c/a/PHP/PHP-Composite-View-Design-Pattern-Introducing-the-Key-Concepts/1/)中获取此信息。无论如何,我有点混淆,$this->$name = $value;陈述。

我通常在类的属性和/或在所述类中调用类的方法时使用$this。加上声明有两个$。这很奇怪!那么$this->$name = $value是指foreach循环中定义的$name吗?如果是这样,有人可以解释这背后的用法或逻辑吗?

提前谢谢。

4 个答案:

答案 0 :(得分:2)

中的$ name
$this->$name = $value

将定义为$ name的变量设置为$ value

E.g。如果$ name ='user',那么这相当于

$this->user = value;

在foreach循环中经常使用这种语法(如上所示)来设置对象值。

注意:每次调用$ this-> variable_name时,如果'variable_name'尚未定义为对象的属性,则调用magic __set函数,并将'variable_name'作为参数传递。

请参阅http://php.net/manual/en/language.oop5.overloading.php

答案 1 :(得分:1)

我没有去你发布的链接,而是阅读代码。

我会举个例子:

// If $data has the following values
array(
    'firstname' => 'my first name',
    'surname'  => 'my surname'
)

代码将'firstname'和'surname'作为该类的公共属性。 $this->firstname的值将是“我的名字”。 $this->surname的值将是“我的姓”。

答案 2 :(得分:0)

$ name包含name of property没有别的

而不是仅仅静态地提及属性,它指向包含属性名称

的变量
$name='someproperty';

$this->$name;

答案 3 :(得分:0)

假设$ name的当前值为“foo”。 然后$ this-> name将返回与$ this-> foo。

完全相同的名称