执行如下代码:
<?php class Test { private $property; function __destruct() { echo "Destroying ".$this->$property."<br />"; } function __set($name,$value) { $this->$name = $value; } } $a = new Test(); $a->property = 5; ?>
报错:Fatal error: Cannot access empty property in /var/www/html/test.php on line 8
将 $this->$property 改为 $this->property ,代码正常执行,输出Destroying 5
疑问:为什么__set函数中可以$this->$name,而前面用$this->$property却报错?
PHP accesses attributes in the definition of a class. Why is "$" sometimes added to the attribute name, but sometimes not? -PHP Chinese website Q&A-When PHP accesses attributes in the definition of a class, why does "$" sometimes need to be added to the attribute name, but sometimes not? -PHP Chinese website Q&A
Let’s take a look and learn.
在__set()方法中,你设置__set("a", 1),$name作为局部变量,会转化为"a", $this->$name等价于$this->a,
在__destruct()中, 局部变量$property未定义,会有一个默认值"",属性值不能为空字符串,所以报错。