2016-03-13 62 views
2

我有以下代碼(來自Zend的認證練習拍攝):值echo語句內改變

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

大部分輸出我明白的,但第一echo聲明我沒有 - 輸出如何可能以「A」以外的任何其他開始?畢竟,a是一個公共屬性,它是正確定義的,因此不會調用__get,即使它被調用,我仍然不知道它將如何輸出「b」。

如果我改變了第一回聲聲明只是:

echo $m->a; 

它輸出:

A 

正如預期的那樣。所以這個值在(完整)echo語句中改變,大概是與優先級有關。

對這個輸出的完整解釋真的很感興趣。謝謝!

回答

2

你行:

echo $m->a ."," .$m->b ."," .$m->c .","; 

也可以這樣寫:

$text = $m->a ."," .$m->b ."," .$m->c .","; 
echo $text; 

如上所述,命令的行爲更加清晰:

首先字符串是串聯,然後串聯的字符串被打印:

$m->a =>        'A,' is added to string 
$m->b => __get() print 'b,' then 'B,' is added to string 
$m->c => __get() print 'c,' then 'C,' is added to string 
echo => print 'A,B,C' (concatenated string) 
+0

的代碼是從Zend認證的練習,我不是要得到不同的結果,我只是想知道爲什麼輸出是因爲它是 – DJC

+0

是的,我知道。解釋不清楚? – fusion3k

+0

好吧,打印立即執行,而回聲將首先連接? – DJC