2011-05-29 63 views
1

我不知道我在哪里做错了。有人可以告诉我吗?__get和__set代码的问题

<?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 
?> 
+0

虽然这两个魔术方法都得心应手保持记住很多人(包括我在内),不推荐的使用它们,因为它们[打破对象封装](http://en.wikipedia.org/wiki/Encapsulation_object-oriented_programming)。 – stefgosselin 2011-05-29 21:10:11

+1

请参阅[这篇文章的正确使用示例](http://stackoverflow.com/questions/3634748/php-zend-say-avoid-magic-methods)尊重封装。 – stefgosselin 2011-05-29 21:17:32

回答

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; 
+0

谢谢,但由于某种原因,这是输出:'attr1 attr2增加了一些更多添加更多东西'。为什么添加“添加更多”两次? – Tarik 2011-05-29 21:06:14

+1

@Braveyard:你可以运行你正在尝试的代码[ideone.com](http://ideone.com/)并发布链接?我得到的输出是['attr1attr2添加了更多东西](http://ideone.com/ibf9U)。 – 2011-05-29 21:07:51

+0

我不知道,但这是相同的代码,这是返回:http://ideone.com/gv6g9 – Tarik 2011-05-29 21:12:04