我在Zend 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
”。我无法弄清楚为什么 - 也许你呢?我的意图是$ m-&gt; a的第一次调用会导致结果“a”,但这显然是错误的......
答案 0 :(得分: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
的字符串。