PHP在类的定义中访问属性,为什么属性名有时要加"$",有时却不用?
phpcn_u274
phpcn_u274 2017-02-16 13:06:39
0
2
1090

执行如下代码:

<?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却报错?

phpcn_u274
phpcn_u274

reply all(2)
数据分析师

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未定义,会有一个默认值"",属性值不能为空字符串,所以报错。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!