I have this question from the Zend PHP study guide and can't find a proper explanation...
<?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;
?>
According to the guide, solution shall be "b,c,A,B,C,c: CC,b,c,A,B,C
". I can't figure out why - maybe you do? My intention is that the first call of $m->a would lead to result "a", but that is obviously wrong...
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that. __FUNCTION__ returns only the name of the function. while as __METHOD__ returns the name of the class alongwith the name of the function.
Magic methods are special methods which override PHP's default's action when certain actions are performed on an object. All methods names starting with __ are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.
__get() is utilized for reading data from inaccessible properties.
Since __get()
calls echo
, some data is being outputted before the echo
outside of the class gets called.
Stepping through the first line with echo
, this is how it gets executed:
$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
At this point, b,c,
has already been echo
ed, and the string with the value of A,B,Cm
is now displayed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With