Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
class A { protected $bar = 'bar'; public function foo() { echo $this->$bar; } } $a = new A(); $a->foo();
令人难以置信的是,这不起作用。我来自 C++ 和 C#,所以我可能对 PHP 不太了解。
为什么这个简单的代码会产生“未定义的变量:bar”
$bar因为 PHP 会在评估之前尝试评估变量$this->。由于没有$bar变量,它会产生一个通知。
$bar
$this->
删除$前面的$bar:
$
echo $this->bar;
我鼓励您阅读文档的变量变量部分以及OOP 基础知识。
访问会员时,只需要前面的美元符号this;即像这样访问它:
this
试试这个
public function(){ echo $this->bar; }
使用 $this 时,不能$在变量之前使用符号,$this->$variable 但是$this->variable;
$this->$variable
$this->variable;