__get和__set代码有问题

时间:2011-05-29 21:00:07

标签: php

我不知道自己哪里做错了。有人能告诉我吗?

<?php 
    class something
    {
        public $attr1;
        private $attr2;

        public function __get($name)
        {
            return $this->$name;
        }

        public function __set($name,$value)
        {
            $this->$name = $value." added something more";
        }
    }

    $a = new something();

    $a->$attr1 = "attr1";
    $a->$attr2 = "attr2";

    echo $a->$attr1; //what I would expect is attr1 as output
    echo $a->$attr2; //what I would expect is attr2 added something more as output
?>

1 个答案:

答案 0 :(得分:6)

访问对象属性时删除$的多个实例:

$a->$attr1 = "attr1";          $a->attr1 = "attr1";
$a->$attr2 = "attr2";          $a->attr2 = "attr2";

echo $a->$attr1;               echo $a->attr1;
echo $a->$attr2;               echo $a->attr2;