Search code examples
phpmagic-methodszend-certification

PHP magic methods example


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


Solution

  • 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 echoed, and the string with the value of A,B,Cm is now displayed.