2011-12-09 80 views
10

我從Zend PHP學習指南這個問題,並不能找到一個合適的解釋...PHP魔術方法例如

<?php 
    class Magic { 
     public $a = "A"; 
     protected $b = array("a"=>"A", "b"=>"B", "c"=>"C"); 
     protected $c = array(1,2,3); 

     public function __get($v) { 
      echo "$v,"; 
      return $this->b[$v]; 
     } 
     public function __set($var, $val) { 
      echo "$var: $val,"; 
      $this->$var = $val; 
     } 
    } 

    $m = new Magic(); 
    echo $m->a.",".$m->b.",".$m->c.","; 
    $m->c = "CC"; 
    echo $m->a.",".$m->b.",".$m->c; 
?> 

據導遊介紹,解決方案應爲「b,c,A,B,C,c: CC,b,c,A,B,C」。我無法弄清楚爲什麼 - 也許你會這樣做?我的本意是,$間的第一個電話>一會導致產生「一」,但顯然是錯誤的...

+0

您提供的代碼會輸出「b,c,A,B,Cmc:CC,b,c,A,B,C'」(參見[this proof](http://codepad.org/) ez1rSs63))。這是指南的錯誤還是確切內容? – Tadeck

+0

你是對的 - 小錯字。這是正確的http://codepad.org/H91fpj8q –

回答

14

由於__get()電話echo,一些數據在echo外類的輸出前被調用。

通過與echo第一線步進,這是它如何被執行:

$m->a "A" is concatenated 
","  "," is concatenated 
$m->b "b," is echoed, "B" is concatenated 
","  "," is concatenated 
$m->c "c," is echoed, "C" is concatenated 
"m"  "," is concatenated 

在這一點上,b,c,已是echo版,和現在顯示與A,B,Cm值的字符串。

+0

是的,就是這樣 - 我今天完成了,完全錯過了! –

+0

+1更好的解釋。 –

+0

太棒了!非常感謝。但是,如果那個出現在考試中... :) 感謝你們! –