![](/img/trans.png)
[英]What is the difference between if ($this-> _hasParam('name') and if($this->_getParam('name')), Zend
[英]What is the difference between `$this->name` and `$this->$name`?
我想知道$this->name
和$this->$name
$this->name
$this->$name
什么区别? $this
也必须严格命名为this还是可以是任何东西?
$this
是保留的变量名,不能用于其他任何用途。 它专门将您指向当前正在使用的对象。您必须使用$this
因为您不知道将分配给哪个变量对象。
$this->name
引用当前类的变量name
$this->$name
表示$name
的值是什么的类变量。 从而
$name = "name";
echo $this->$name; // echos the value of $this->name.
$name = "test";
echo $this->$name; // echos the value of $this->test
$ this是PHP中使用的保留名称,它指向您在(用引号引起来 )的类的当前实例:
从对象上下文中调用方法时,伪变量
$this
可用。
$this
是对调用对象的引用(通常是该方法所属的对象,但如果从辅助对象的上下文中静态调用该方法,则可能是另一个对象)。
当使用$this->name
,您正在访问的名称属性name
当前对象的。
使用$this->$name
,$ name是在访问属性之前确定的-这意味着您将访问属性,该名称包含在$name
局部变量中。
例如,使用这部分代码:
$name = 'abc';
echo $this->$name;
实际上,您将回显abc属性的内容,就像您已经编写了:
echo $this->abc;
在执行此操作时,您正在使用变量变量 (引用) :
也可以使用变量属性名称来访问类属性。
变量属性名称将在进行调用的范围内解析。
例如,如果您有一个表达式,例如$foo->$bar
,那么将检查本地范围中的$bar
并将其值用作$foo
属性的名称。
如果$ bar是数组访问,也是如此。
更新后才弹出此问题。 我喜欢这个问题,所以我想添加自己的差异示例。
class Test
{
public $bar = 'bar';
public $foo = 'foo';
public function __construct()
{
$bar = 'foo';
$this->bar; // bar
$this->$bar; // foo
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.