2011-05-29 28 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

相關問題