我正在为考试做一些 PHP 问题,在下面的问题中,显然 (B) 就是答案。
What is the output of the following code?
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;
- A: A,Array,Array,A,Array,Array,CC
- B: b,c,A,B,C,c: CC,b,c,A,B,C
- C: a,b,c,A,B,C,c: CC,a,b,c,A,B,C
- D: b,c,A,B,C,c: CC,b,c,A,B,CC
很抱歉问了这个菜鸟问题,但我来自 Java,我无法理解为什么这是正确的答案。
最佳答案
$b
和 $c
是 protected 属性,因此无法从类范围之外设置它们。 $a
是公共(public)的,因此可以直接设置/访问。
为了访问 $b
和 $c
,它将回退到 magic getter,从 $b
数组中检索值。
逻辑如下:
b, <- getter echo (executed by $m->b)
c, <- getter echo (executed by $m->c)
A, <- public property value (this is the start of the first global echo expression)
B, <- getter return b[b]
C, <- getter return b[c]
c: CC, <- setter echo, sets c = CC, but c is never accessed
b, <- getter echo (executed by $m->b)
c, <- getter echo (executed by $m->c)
A, <- public property value (this is the start of the second global echo expression)
B, <- getter return b[b]
C <- getter return b[c]
首先处理 getter 回显,因为在回显表达式(带有串联)完成评估之前就到达了它们的 echo 语句。
由于 $a
是公共(public)的,因此不使用魔术 setter 或 getter。
关于php - (PHP) 为什么这是以下 echo 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53602626/