如果之前有人问过这个问题,请原谅,但我尝试搜索它没有令人满意的结果。
我正在学习 PHP(来自 C++ 背景)并且遇到了以下歧义。以下两位代码的工作方式完全相同:
class A
{
public $myInteger;
public function __get($name)
{
return $this->$name;
}
public function __set($name, $value)
{
$this->$name = $value;
}
}
和
class A
{
public $myInteger;
public function __get($name)
{
return $this->name;
}
public function __set($name, $value)
{
$this->name = $value;
}
}
也就是在类中的方法$this->$name
和$this->name
具有完全相同的功能。我发现这有点令人困惑,尤其是考虑到如果您添加以下代码,
$myA = new A();
$myA->myInteger = 5;
$hereInt = $myA->myInteger;
echo "<p>" . $hereInt . "</p>";
它只有在没有$
before时才有效myInteger
。有人可以解释一下这背后的理由吗?