Zend Certified PHP Engineer (ZCE) PHP 5.5 — Question 2
Consider the following code. What change must be made to the class for the code to work as written? class Magic { protected $v = array("a" => 1, "b" => 2, "c" => 3); public function __get($v) { return $this->v[$v];
}
}
$m = new Magic();
$m->d[] = 4;
echo $m->d[0];
Answer options
- A. Nothing, this code works just fine.
- B. Add __set method doing $this->v[$var] = $val
- C. Rewrite __get as: public function __get(&$v)
- D. Rewrite __get as: public function &__get($v)
- E. Make __get method static
Correct answer: D
Explanation
The correct answer is D because the __get method needs to return a reference to the requested value in order for the assignment operation ($m->d[] = 4) to work correctly. Options A and E are incorrect because they do not address the need for reference return, while B and C suggest changes that do not solve the problem with the current assignment.